gpt4 book ai didi

wpf - 在 IValueConverter 类中定义属性

转载 作者:行者123 更新时间:2023-12-02 19:03:37 25 4
gpt4 key购买 nike

我需要在转换器类中定义 DependencyProperty,因为我需要此数据来进行转换,并且此数据位于另一个对象中,而不是我绑定(bind)到的对象中。

我的转换器类如下:

public class LEGOMaterialConverter   : DependencyObject, IValueConverter
{
public DependencyProperty MaterialsListProperty = DependencyProperty.Register("MaterialsList", typeof(Dictionary<int, LEGOMaterial>), typeof(LEGOMaterialConverter));

public Dictionary<int, LEGOMaterial> MaterialsList
{
get
{
return (Dictionary<int, LEGOMaterial>)GetValue(MaterialsListProperty);
}
set
{
SetValue(MaterialsListProperty, value);
}
}

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
LEGOMaterial material = null;

MaterialsList.TryGetValue((int)value, out material);

return material;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

然后我在 Window.REsources 区域实例化它:

<Window.Resources>
<local:LEGOMaterialConverter x:Key="MaterialsConverter" MaterialsList="{Binding Path=Materials}" />
</Window.Resources>

我收到以下错误:

   'MaterialsList' property was already registered by 'LEGOMaterialConverter'.

有人知道这个错误吗?

最佳答案

尝试这样做(只是一个例子):

public class ValueConverterWithProperties : MarkupExtension, IValueConverter
{
public int TrueValue { get; set; }

public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((int) value == TrueValue)
{
return true;
}
return false;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

请注意,我从标记扩展派生,允许我像这样使用它:

<Window x:Class="Converter.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:converter="clr-namespace:Converter"
Title="MainWindow" Height="350" Width="525">
<Grid>
<CheckBox IsChecked="{Binding item, Converter={converter:ValueConverterWithProperties TrueValue=5}}"></CheckBox>
<CheckBox IsChecked="{Binding item2, Converter={converter:ValueConverterWithProperties TrueValue=10}}"></CheckBox>
</Grid>

关于wpf - 在 IValueConverter 类中定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28141791/

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