2010-12-12 91 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>