2009-08-19 90 views
0

我这是在我的视图模型约束,并设置为一个ObservableCollection一个ItemsControl:如何获取MVVM绑定的单选按钮的选定索引?

<ItemsControl ItemsSource="{Binding AwaySelection}" > 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <RadioButton Content="{Binding AwayText}" ></RadioButton> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 

现在,如何找出被点击哪一个?我想将每个Radiobutton的IsChecked值绑定到viewmodel中的一个变量,该变量返回集合的索引。这将使我很容易直接引用选定的项目。有任何想法吗?

回答

1

这就是我解决这个问题的方法。我写了一个EnumToBool转换器对于这一点,像

public class EnumToBoolConverter : IValueConverter 
    { 
     #region IValueConverter Members 

     public object Convert(object value, 
      Type targetType, object parameter, 
      System.Globalization.CultureInfo culture) 
     { 
      if (parameter.Equals(value)) 
       return true; 
      else 
       return false; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      return parameter; 

     } 
     #endregion 

    } 

而且我已经下面列举

public enum CompanyTypes 
    { 
     Type1Comp, 
     Type2Comp, 
     Type3Comp 
    } 

现在,在我的XAML中,我传递的类型作为参数转换。

<Window x:Class="WpfTestRadioButtons.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfTestRadioButtons" 
    Title="Window1" Height="300" Width="300"> 
    <Window.Resources> 
     <local:EnumToBoolConverter x:Key="EBConverter"/> 
    </Window.Resources> 
    <Grid> 
     <StackPanel> 
      <RadioButton IsChecked="{Binding Path=Type, 
       Converter={StaticResource EBConverter}, 
       ConverterParameter={x:Static local:CompanyTypes.Type1Comp}}" Content="Type1"/> 
      <RadioButton IsChecked="{Binding Path=Type, 
       Converter={StaticResource EBConverter}, 
       ConverterParameter={x:Static local:CompanyTypes.Type2Comp}}" Content="Type2"/> 
     </StackPanel> 

    </Grid> 
</Window> 

现在,在您的视图模型中,您应该有一个属性(在这种情况下为Type),该属性是Enum类型。

一样,

public CompanyTypes Type 
     { 
      get 
      { 
       return _type; 
      } 
      set 
      { 
       _type = value; 
       if (PropertyChanged != null) 
        PropertyChanged(this, new PropertyChangedEventArgs("Type")); 

      } 
     } 

在这个例子中,你可能已经注意到,单选按钮是静态的。在你的情况中,当你列出Item控件中的单选按钮时,你需要将你的RadioButton的ConverterParameter绑定到正确的类型。

0

当使用MVVM用单选按钮控制退出的方法onToggle()的一个问题,但你可以创建一个单选按钮。

public class DataBounRadioButton: RadioButton 
    { 
     protected override void OnChecked(System.Windows.RoutedEventArgs e) { 

     } 

     protected override void OnToggle() 
     { 
      this.IsChecked = true; 
     } 
    } 

然后添加控件和绑定属性的引用,在我的情况IsActive。

<controls:DataBounRadioButton 
         IsChecked="{Binding IsActive}"/> 
相关问题