In principle, I developed a neat way to bind RadioButtons to almost anything:
/// <summary>Converts an value to 'true' if it matches the 'To' property.</summary>
/// <example>
/// <RadioButton IsChecked="{Binding VersionString, Converter={local:TrueWhenEqual To='1.0'}}"/>
/// </example>
public class TrueWhenEqual : MarkupExtension, IValueConverter
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
public object To { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return object.Equals(value, To);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value) return To;
throw new NotSupportedException();
}
}
For example, you can use this to bind RadioButtons to a string property as follows (it is a well-known bug that you must use a unique GroupName for each RadioButton):
<RadioButton GroupName="G1" Content="Cat"
IsChecked="{Binding Animal, Converter={local:TrueWhenEqual To='CAT'}}"/>
<RadioButton GroupName="G2" Content="Dog"
IsChecked="{Binding Animal, Converter={local:TrueWhenEqual To='DOG'}}"/>
<RadioButton GroupName="G3" Content="Horse"
IsChecked="{Binding Animal, Converter={local:TrueWhenEqual To='HORSE'}}"/>
Now, I would like to use public static readonly
objects called Filter1
and Filter2
as the values of my RadioButtons. So I tried:
<RadioButton GroupName="F1" Content="Filter Number One"
IsChecked="{Binding Filter, Converter={local:TrueWhenEqual To='{x:Static local:ViewModelClass.Filter1}'}}"/>
<RadioButton GroupName="F2" Content="Filter Number Two"
IsChecked="{Binding Filter, Converter={local:TrueWhenEqual To='{x:Static local:ViewModelClass.Filter2}'}}"/>
But this gives me an error:
Unknown property 'To' for type
'MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension'
encountered while parsing a Markup Extension.
The error still occurs if I remove the quotes. What am I doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…