Defining a Property in a IValueConverter class

不羁的心 提交于 2019-12-05 08:24:37

Try doing it like this (just an example):

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();
    }
}

notice I derive from markup extension to allow me to use it like this:

<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>

Btw, this error is caused by your dependency property in the converter not being static (and after having created an instance of this converter somewhere before).

EDIT

So the problem is with this line:

public DependencyProperty MaterialsListProperty = DependencyProperty.Register("MaterialsList", typeof(Dictionary<int, LEGOMaterial>), typeof(LEGOMaterialConverter));

Here the Dependency Property MaterialsListProperty is being registered with every instantiation of an object of this type (i.e. LEGOMaterialConverter).

However Dependency Properties should be defined static, like so:

public static readonly DependencyProperty MaterialsListProperty = DependencyProperty.Register("MaterialsList", typeof(Dictionary<int, LEGOMaterial>), typeof(LEGOMaterialConverter));

A static variable is initialized (and the Dependency Property is registered) only once for all future instances of this type and that is what we need here. Failing to declare a Dependency Property as static results in the error from above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!