如何擁有一個屬性並使用轉換器管理多個值。例如:
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" };
}
}
IMO將您的模型的數據類型更改爲枚舉。對於單選按鈕的相互排斥選擇更有意義,並且用wpf表示它可以呈現枚舉的所有選項。 – 2010-12-04 06:08:46