2009-08-19 91 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}"/> 
相關問題