问题
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?
回答1:
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;
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/48539313/valueconverter-with-properties