GregorMohorko
GregorMohorko

Reputation: 2857

Why isn't a class converted automatically in DataGrid when implicit conversion exists?

I have a class MyClass with one property: MyProperty of type MyPropertyClass. MyPropertyClass has implicit operator for converting from string.

Now I want to bind to that property from a DataGridTextColumn in a two-way, but it doesn't work. In my opinion, it should automatically convert from string to MyPropertyClass and also back (using ToString method).

Error:

System.Windows.Data Error: 1 : Cannot create default converter to perform 'two-way' conversions between types 'Test.MyPropertyClass' and 'System.String'. Consider using Converter property of Binding. BindingExpression:Path=MyProperty; DataItem='MyClass' (HashCode=22558296); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')

I know that I could define a Converter like the error description above states. But doing this is redundant as I would only use the implicit conversion from string to MyPropertyClass and the ToString method anyway.

Code:

class MyClass
{
    public MyPropertyClass MyProperty { get; set; }
}

class MyPropertyClass
{
    private string value;

    public override string ToString()
    {
        return value;
    }

    public static implicit operator MyPropertyClass(string s)
    {
        MyPropertyClass mc = new MyPropertyClass();
        mc.value = s;
        return mc;
    }
}

XAML:

<DataGrid ItemsSource="{Binding List,Mode=OneWay}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="My Property" Binding="{Binding MyProperty,Mode=TwoWay}" />
    </DataGrid.Columns>
</DataGrid>

Upvotes: 1

Views: 54

Answers (1)

AnjumSKhan
AnjumSKhan

Reputation: 9827

You are looking for a TypeConverter.

  1. CodeProject
  2. Wpf2000things

Upvotes: 1

Related Questions