我有一个类MyClass
与一个属性:MyProperty
类型MyPropertyClass
。 MyPropertyClass
有implicit operator
从string
转换。当存在隐式转换时,为什么不在DataGrid中自动转换类?
现在我想从DataGridTextColumn
的双向绑定到该属性,但它不起作用。在我看来,它应该自动从string
转换为MyPropertyClass
,并且还会返回(使用ToString
方法)。
错误:
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')
我知道我可以定义一个Converter
像上面状态的错误描述。但是这样做是多余的,因为我只会使用从string
到MyPropertyClass
和ToString
方法的implicit conversion
。
代码:
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>
感谢您指出了这一点,但我仍然认为,写这些转换器是多余的。我的意思是:无论如何,我将使用'隐式转换'和'ToString'方法。为什么它不能自动完成? – GregaMohorko