2015-05-26 29 views
0

首先,我是WPF的新手,我正在使用MVVM Light Toolkit,并且大约2天了,现在我在拼凑互联网,试图找到一个简单的方法来创建一个单选按钮列表。我发现很多例子在我看来都很复杂,或者是对一些旧bug或者甚至是非工作例子的“黑客”。什么是最简单的WPF数据绑定单选按钮列表的方法

比方说,在你的代码隐藏你有一个字符串

List<string> options = new List<string>(); 

     options.Add("option 1"); 
     options.Add("option 2"); 
     options.Add("option 3"); 
     options.Add("option 4"); 

所以我要问你的这份名单中,有什么是创建options一个单选按钮列表的最简单的方法?

回答

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> 
1

试试下面的代码示例: -

<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; } 

    } 
相关问题