I need to define a DependencyProperty in a converter class because I need this data to make the conversion and this data is in another object, not the one I'm binding to.
My converter class is the following:
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();
}
}
Then I'm instanciating it on the Window.REsources area:
<Window.Resources>
<local:LEGOMaterialConverter x:Key="MaterialsConverter" MaterialsList="{Binding Path=Materials}" />
</Window.Resources>
I'm getting the following error:
'MaterialsList' property was already registered by 'LEGOMaterialConverter'.
Does anyone have a clue on this error?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With