2010-12-12 102 views
9

我在我的程序中有一个ItemsControl,其中包含单选按钮列表。获取组中的选定单选按钮(WPF)

<ItemsControl ItemsSource="{Binding Insertions}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Grid> 
        <RadioButton GroupName="Insertions"/> 
       </Grid> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 

如何找到Insertions在MVVM方式在选定的单选按钮?

我在互联网上找到的大多数示例都涉及到设置单个布尔属性,您可以在转换器的帮助下将IsChecked属性绑定到该属性。

有没有相当于我可以绑定的ListBoxSelectedItem

回答

9

想到的一个解决方案是向插入实体添加一个IsChecked布尔属性,并将其绑定到单选按钮的“IsChecked”属性。这样你可以检查View Model中的'Checked'单选按钮。

这里是一个快速和肮脏的例子。

注:我忽略的事实,也器isChecked可以null,你可以处理,使用bool?如果需要的话。

简单视图模型

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 

namespace WpfRadioButtonListControlTest 
{ 
    class MainViewModel 
    { 
    public ObservableCollection<Insertion> Insertions { get; set; } 

    public MainViewModel() 
    { 
     Insertions = new ObservableCollection<Insertion>(); 
     Insertions.Add(new Insertion() { Text = "Item 1" }); 
     Insertions.Add(new Insertion() { Text = "Item 2", IsChecked=true }); 
     Insertions.Add(new Insertion() { Text = "Item 3" }); 
     Insertions.Add(new Insertion() { Text = "Item 4" }); 
    } 
    } 

    class Insertion 
    { 
    public string Text { get; set; } 
    public bool IsChecked { get; set; } 
    } 
} 

的XAML - 背后的代码中未示出,因为它具有不超过比所生成的代码的其他代码。

<Window x:Class="WpfRadioButtonListControlTest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfRadioButtonListControlTest" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
    <local:MainViewModel x:Key="ViewModel" /> 
    </Window.Resources> 
    <Grid DataContext="{StaticResource ViewModel}"> 
    <ItemsControl ItemsSource="{Binding Insertions}"> 
     <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
      <RadioButton GroupName="Insertions" 
         Content="{Binding Text}" 
         IsChecked="{Binding IsChecked, Mode=TwoWay}"/> 
      </Grid> 
     </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
    </Grid> 
</Window>