我有一个WPF-MVVM应用程序......
我有3个单选按钮控件 - 有三个选项=> “个人”,“群体”和“两者”。 所有3个都有相同的组名...这意味着只能选择其中一个单选按钮。
我可以在viewmodel中有三个属性...对于这三个选项中的每一个...并且可以检查选择了哪一个。
Function()
{
if (Is_Individual_property)
{
// Individual selected
}
if (Is_Group_property)
{
// group selected
}
if (Is_Both_property)
{
// Both selected
}
}
但我认为这是不最佳方法。
我可以在viewmodel中只有一个属性并相应地绑定值吗?
答案 0 :(得分:21)
如何使用转换器拥有单个属性并管理多个值。例如:
XAML:
<Grid>
<Grid.Resources>
<local:BooleanToStringValueConverter x:Key="BooleanToStringValueConverter" />
</Grid.Resources>
<StackPanel>
<TextBlock Text="{Binding Property1}" />
<RadioButton Name="RadioButton1"
GroupName="Group1"
Content="Value1"
IsChecked="{Binding Path=Property1, Converter={StaticResource BooleanToStringValueConverter}, ConverterParameter=Value1}" />
<RadioButton Name="RadioButton2"
GroupName="Group1"
Content="Value2"
IsChecked="{Binding Path=Property1, Converter={StaticResource BooleanToStringValueConverter}, ConverterParameter=Value2}" />
<RadioButton Name="RadioButton3"
GroupName="Group1"
Content="Value3"
IsChecked="{Binding Path=Property1, Converter={StaticResource BooleanToStringValueConverter}, ConverterParameter=Value3}" />
</StackPanel>
</Grid>
转换器:
public class BooleanToStringValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (System.Convert.ToString(value).Equals(System.Convert.ToString(parameter)))
{
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (System.Convert.ToBoolean(value))
{
return parameter;
}
return null;
}
}
类别:
public class MyClass : INotifyPropertyChanged
{
private String _property1;
public String Property1
{
get { return _property1; }
set { _property1 = value; RaisePropertyChanged("Property1"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}
窗口:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MyClass() { Property1 = "Value1" };
}
}