使用模板创建RadioButton-List控件
前言:本文通过一个简单控件的创建,来看看silverlight的模板系统到底有多么强大(当然这只是强大之处的一点点点....)写作本文的灵感来自于我在互联网上闲逛,看到有朋友需要这样的需求,同时也想通过此练习来学习silverlight,但最希望的是本文能对有需要的朋友有所帮助。
控件需求:使用单选按钮来显示条目和接受选择的列表框
大概样子如下:
方案一:通过silverlight的元素合成思想
这个控件可以由以下两元素合成:
1:RadioButton
2:ListBox
于是,最简单的代码就出来了:
<RadioButton Content="单选按钮一"/>
<RadioButton Content="单选按钮二"/>
<RadioButton Content="单选按钮三"/>
<RadioButton Content="单选按钮四"/>
</ListBox>
看看效果吧:
看起来还不错~~那如果,我们的需求有变化,需要默认选择第一个单选按钮,那继续改改吧:

<ListBoxItem IsSelected="True">
<RadioButton Content="单选按钮一"/>
</ListBoxItem>
<RadioButton Content="单选按钮二"/>
<RadioButton Content="单选按钮三"/>
<RadioButton Content="单选按钮四"/>
</ListBox>
结果如下:
列表项第一个是被选中了,但是单选按钮仍旧没有被选中,那我们就继续改改:

<ListBoxItem>
<RadioButton Content="单选按钮一" IsChecked="True"/>
</ListBoxItem>
<RadioButton Content="单选按钮二"/>
<RadioButton Content="单选按钮三"/>
<RadioButton Content="单选按钮四"/>
</ListBox>
把第一个按钮默认是选中的,看下结果:
默认选中是可以了,但是,当我们点击第二个按钮的时候,发现第一个按钮还是选中的,这个问题好解决,把单选按钮归为一组就行了:
<ListBoxItem >
<RadioButton Content="单选按钮一" IsChecked="True" GroupName="go"/>
</ListBoxItem>
<RadioButton Content="单选按钮二" GroupName="go"/>
<RadioButton Content="单选按钮三" GroupName="go"/>
<RadioButton Content="单选按钮四" GroupName="go"/>
</ListBox>
这样,一个目标需求的控件也算是合成了,但是其实它算不上正真意义上的控件,当你点击列表项的时候,单选按钮是不会被选中的,除非你点击列表项中的单选按钮,这样才能选中。其实也挺强大了,这里是把RadionButton作为ListBox的内容控件。那么,接下来,让我们再来看看运用模板技术来更好的实现这个目标需求。
方案二:利用模板技术和绑定技术来实现
需要用到ListBox的ItemContainerStyle属性:
获取或设置在呈现项容器时使用的样式。
C# |
---|
public Style ItemContainerStyle { get; set; } |
XAML 属性元素用法 |
---|
<ListBox> <ListBox.ItemContainerStyle> inlineStyle </ListBox.ItemContainerStyle> </ListBox> |
然后制作ListBoxItem的模板,把它的模板内容设定为RadionButton,然后把RadioButton的IsChecked属性绑定到ListBoxItem的IsSelected属性上:

<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<RadioButton IsChecked="{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent}}"
Content="{TemplateBinding Property=Content}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBoxItem IsSelected="True">
<TextBlock>单选按钮一</TextBlock>
</ListBoxItem>
<TextBlock>单选按钮二</TextBlock>
<TextBlock>单选按钮三</TextBlock>
<TextBlock>单选按钮四</TextBlock>
</ListBox>
这样,当你选择列表项的时候,按钮的选中属性就会随着列表项的改变而改变,并且单选按钮也不需要分组了,因为这里它不是列表控件的内容控件了。看下最终效果:
|
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构