原则上,我开发了一种将 RadioButtons 绑定到几乎任何东西的简洁方法:
/// <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();
}
}
例如,您可以使用它来将 RadioButtons 绑定到字符串属性,如下所示(这是一个众所周知的错误,您必须为每个 RadioButton 使用唯一的 GroupName):
<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'}}"/>
现在,我想使用public static readonly
名为Filter1
和的对象Filter2
作为我的 RadioButtons 的值。所以我尝试了:
<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}'}}"/>
但这给了我一个错误:
解析标记扩展时遇到类型“MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension”的未知属性“To”。
如果我删除引号,错误仍然会发生。我究竟做错了什么?