gpt4 book ai didi

wpf - 使用标记扩展绑定(bind)时出错 : Unknown property encountered while parsing a Markup Extension

转载 作者:行者123 更新时间:2023-12-04 13:27:25 25 4
gpt4 key购买 nike

原则上,我开发了一种将 RadioButtons 绑定(bind)到几乎任何东西的简洁方法:

/// <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 绑定(bind)到字符串属性,如下所示(这是一个众所周知的错误,您必须为每个 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}'}}"/>

但这给了我一个错误:

Unknown property 'To' for type 'MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension' encountered while parsing a Markup Extension.



如果我删除引号,错误仍然会发生。我究竟做错了什么?

最佳答案

WPF 不能很好地处理嵌套标记扩展。为了克服这个问题,您可以使用您的标记扩展作为一个元素。它有点笨拙且难以阅读,但它有效:

<RadioButton GroupName="F1" Content="Filter Number One">
<RadioButton.IsChecked>
<Binding Path="Filter">
<Binding.Converter>
<local:TrueWhenEqual To={x:Static local:ViewModelClass.Filter1} />
</Binding.Converter>
</Binding>
</RadioButton.IsChecked>
</RadioButton>

另一种方法是声明您的转换器并将其用作静态资源:
<Window.Resources>
<local:TrueWhenEqual To={x:Static local:ViewModelClass.Filter1} x:Key="myConverter" />
</Window.Resources>

<RadioButton GroupName="F1" Content="Filter Number One"
IsChecked="{Binding Filter, Converter={StaticResource myConverter}}" />

关于wpf - 使用标记扩展绑定(bind)时出错 : Unknown property encountered while parsing a Markup Extension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11785248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com