原則,我發展到單選按鈕綁定到幾乎任何一種巧妙的方法:錯誤使用標記擴展綁定時:未知屬性遇到在解析標記擴展
/// <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();
}
}
例如,你可以用它來綁定單選按鈕一個字符串屬性,如下所示(這是一個衆所周知的錯誤,你必須對每個單選唯一的組名):
<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
作爲值我的Rad ioButtons。所以,我想:
<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}'}}"/>
但是,這給了我一個錯誤:
Unknown property 'To' for type 'MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension' encountered while parsing a Markup Extension.
如果我刪除引號仍然出現錯誤。我究竟做錯了什麼?
第二個環節都有正確答案(我的意思是,簡單的答案)。我只需要定義一個構造函數'public TrueWhenEqual(object to){To = to; }'然後用'Converter = {local:TrueWhenEqual {x:Static local:ViewModelClass.Filter1}}}來調用轉換器。'' – Qwertie 2012-08-02 22:34:39