C# 如何获取MVVM绑定单选按钮的选定索引?
我有一个ItemsControl,它在我的viewmodel中绑定并设置为observablecollection:C# 如何获取MVVM绑定单选按钮的选定索引?,c#,.net,wpf,data-binding,mvvm,C#,.net,Wpf,Data Binding,Mvvm,我有一个ItemsControl,它在我的viewmodel中绑定并设置为observablecollection: <ItemsControl ItemsSource="{Binding AwaySelection}" > <ItemsControl.ItemTemplate> <DataTemplate> <RadioButton Content="{Bi
<ItemsControl ItemsSource="{Binding AwaySelection}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding AwayText}" ></RadioButton>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
现在,如何确定单击了哪一个?我希望将每个Radiobutton的IsChecked值绑定到viewmodel中的单个变量,该变量将索引返回到集合。这将使我很容易直接引用所选项目。有什么想法吗?这就是我解决这个问题的方法。我为此编写了一个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>
在本例中,您可能已经注意到单选按钮是静态的。在您的例子中,当您在Item控件中列出单选按钮时,您还需要将RadioButton的ConverterParameter绑定到正确的类型。最后,我将单选按钮放入listview,并将listview的isselected属性绑定到RadioButton属性
将MVVM与radiobutton控件一起使用时,onToggle()方法存在问题,但您可以为此创建radiobutton
public class DataBounRadioButton: RadioButton
{
protected override void OnChecked(System.Windows.RoutedEventArgs e) {
}
protected override void OnToggle()
{
this.IsChecked = true;
}
}
然后添加对控件的引用并绑定属性,在我的例子中是active
<controls:DataBounRadioButton
IsChecked="{Binding IsActive}"/>
<controls:DataBounRadioButton
IsChecked="{Binding IsActive}"/>