【问题标题】:What is the simplest way to data bound radio button list in WPFWPF中数据绑定单选按钮列表的最简单方法是什么
【发布时间】:2015-05-26 09:42:49
【问题描述】:
首先,我是 WPF 的新手,我正在使用 MVVM Light Toolkit,大约 2 天来,我正在网上搜索,试图找到一种简单的方法来创建单选按钮列表。我发现了许多在我看来过于复杂的示例,要么是针对某些旧错误的“hack”,要么甚至是无效的示例。
假设在你的代码隐藏中有这个字符串列表
List<string> options = new List<string>();
options.Add("option 1");
options.Add("option 2");
options.Add("option 3");
options.Add("option 4");
所以我想问你,用options创建单选按钮列表最简单的方法是什么?
【问题讨论】:
标签:
c#
.net
wpf
xaml
windows-runtime
【解决方案1】:
我认为,最简单的是:
<ItemsControl ItemsSource="{Binding Options}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
其中Options 是数据上下文的属性,如下所示:
public IEnumerable<string> Options
{
get { return options; }
}
但我认为,您会希望获得选择结果。
因此,任务变得更加复杂。你需要视图模型:
public class OptionViewModel
{
public bool? IsChecked { get; set; }
public string OptionName { get; set; }
}
然后,您必须将字符串列表转换为视图模型列表:
public IEnumerable<OptionViewModel> Options
{
get { return optionsAsViewModels ?? (optionsAsViewModels = new List(options.Select(_ => new OptionViewModel { OptionName = _ }))); }
}
private IEnumerable<OptionViewModel> optionsAsViewModels;
并对项目模板进行一些更改:
<ItemsControl ItemsSource="{Binding Options}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding OptionName}" IsChecked="{Binding IsChecked}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
【解决方案2】:
试试下面的代码示例:-
<DataTemplate>
<RadioButton GroupName="Test"
Content="{Binding ItemDescription}"
IsChecked="{Binding IsSelected}"
Margin="5,1"/>
</DataTemplate>
在服务器端:-
public ViewModel()
{
Test = new Collection<SelectableItem>
{
new SelectableItem { ItemDescription = "Option 1"},
new SelectableItem { ItemDescription = "Option 2"},
new SelectableItem { ItemDescription = "Option 3", IsSelected = true},
new SelectableItem { ItemDescription = "Option 4"}
};
}
和
public class SelectableItem : INotifyPropertyChanged
{
public string ItemDescription { get; set; }
public bool IsSelected { get; set; }
}