WPF and SL RadioButtonList Tip
2008-11-03 14:03 Clingingboy 阅读(1245) 评论(0) 编辑 收藏 举报在以下情境下.使用数据绑定分离UI与后端Model,有两个RadioButton,用于选择True or False(如果用CheckBox则就没这么多复杂的问题了).
实现步骤如下,
(1)用ListBox定义一个RadioButton模板
<!--for RadioButton ListBox--> <Style x:Key="HorizontalRadioButtonListStyle" TargetType="ListBox"> <Style.Resources> <Style TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <Grid Margin="2"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <RadioButton IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" /> <ContentPresenter Grid.Column="1" Margin="2,0,0,0" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Style.Resources> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <WrapPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </Setter.Value> </Setter> <Setter Property="BorderThickness" Value="0" /> <Setter Property="Background" Value="Transparent" /> </Style>
(2)定义类型转换器(以传入的参数进行判定)
public class MulitBooleanConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { int serviceParameter =int.Parse(parameter.ToString()); bool isOnservice=(bool)value; bool result = false; switch (serviceParameter) { case 0: result = true && isOnservice; break; case 1: result = !isOnservice; break; } return result; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { int serviceParameter = int.Parse(parameter.ToString()); bool isOnservice = (bool)value; bool result = false; switch (serviceParameter) { case 0: result = true && isOnservice; break; case 1: result = false && isOnservice; break; } return value; } #endregion }
(3)使用如下(同时双向绑定一个属性xxx)
<ListBox Style="{StaticResource HorizontalRadioButtonListStyle}"> <ListBox.Items> <ListBoxItem IsSelected="{Binding xxx,Converter={StaticResource boolConverter},ConverterParameter=0}">在线</ListBoxItem> <ListBoxItem IsSelected="{Binding xxx,Converter={StaticResource boolConverter},ConverterParameter=1}">离线</ListBoxItem> </ListBox.Items> </ListBox>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现