在IValueConverter类中定义属性

RBa*_*iak 5 wpf dependency-properties ivalueconverter

我需要在转换器类中定义DependencyProperty,因为我需要这些数据来进行转换,而这个数据在另一个对象中,而不是我绑定的对象.

我的转换器类如下:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<Window.Resources>
    <local:LEGOMaterialConverter x:Key="MaterialsConverter" MaterialsList="{Binding Path=Materials}" />
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

   'MaterialsList' property was already registered by 'LEGOMaterialConverter'.
Run Code Online (Sandbox Code Playgroud)

有没有人对这个错误有所了解?

Ami*_*Raz 6

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)