ValueConverter with properties [duplicate]

2019-07-25 21:05发布

This question already has an answer here:

Extending the following question:

Defining a Property in a IValueConverter class

My question is:

In the xaml file, TrueValue is set to a single value:

<CheckBox IsChecked="{Binding item, Converter={converter:ValueConverterWithProperties TrueValue=5}}"></CheckBox>

Is it possible to bind a property in a ValueConverter to some kind of List? How would the binding expression look like?

2条回答
Luminary・发光体
2楼-- · 2019-07-25 21:59

You can declare a dependency property in the converter class, declare your converter as static resource and bind the property to a view model property.

This will work:

<Window x:Class="..."
        x:Name="_this" 
        ...>
<Window.Resources>
    <local:DepPropConverter x:Key="Convert"
        MyList="{Binding DataContext.YourListInViewmodel, Source={x:Reference _this}}"/>
</Window.Resources>
<CheckBox IsChecked="{Binding item, Converter={StaticResource Converter}}"></CheckBox>

The converter:

public class DepPropConverter : DependencyObject, IValueConverter
{
    public static readonly DependencyProperty MyListProperty =
        DependencyProperty.Register(
            nameof(MyList), typeof(IList), typeof(DepPropConverter));

    public IList MyList
    {
        get { return (IList)GetValue(MyListProperty); }
        set { SetValue(MyListProperty, value); }
    }

    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        //your logic here
        return value;
    }

    public object ConvertBack(
        object value, Type targetTypes, object parameter, CultureInfo culture)
    {
        //your logic here
        return value;
    }
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-25 22:06

Binding to parameters or properties of IValueConverter does not work AFAIK, but you can use a IMultiValueConverter and just bind the additional values to the desired property:

<MultiBinding Converter="{StaticResource MultiValueConverter}">
    <Binding Path="YourValue" />
    <Binding Path="YourParameter" />
</MultiBinding>

and then use values[0] as the actual value and values[1] as the parameter.

查看更多
登录 后发表回答