Question

I've struggled to understand this error for some time and now it's finally breaking something. Here's a dumbed-down sketch of what I'm doing:

My datawrapper class:

class DummyWrapper<T> : INotifyPropertyChanged
{
    public DummyWrapper() { }

    private T _data;
    public T Data
    {
        get { return _data; }
        set
        {
            _data = value;
            Notify("Data");
        }
    }

    public static implicit operator T(DummyWrapper<T> d)
    {
        return d._data;
    }

    ...
}

My XAML:

<DockPanel>
    <ContentPresenter Name="cp" Visibility="Collapsed"/>
    <Rectangle Name="foo" Fill="{Binding ElementName=cp, Path=Content}" Height="50" Width="50"/>
</DockPanel>

The pertinent bit of my codebehind:

DummyWrapper<Brush> dw = new DummyWrapper<Brush>(new SolidColorBrush((Color)ColorConverter.ConvertFromString("Red")));
cp.Content = dw;

And of course if this was all working the way I expected I wouldn't be here. The output window shows me this:

System.Windows.Data Error: 23 : Cannot convert 'WpfTestApplication.DummyWrapper`1[System.Windows.Media.Brush]' 
from type 'DummyWrapper`1' to type 'System.Windows.Media.Brush' 
for 'en-US' culture with default conversions; consider using Converter property of Binding.

... and it goes on in that vein for some time.

Is there something I can do to allow my DummyWrapper to be converted automatically (ie w/o supplying a converter in the binding) in this context?

Was it helpful?

Solution

Change your line of code to

var solidColorBrush = new SolidColorBrush((Color) ColorConverter.ConvertFromString("Red"));
DummyWrapper<Brush> dw = new DummyWrapper<Brush>(solidColorBrush);
cp.Content = (Brush)dw;

You don't want to use converters that's fine. Content is an object and doing an implicit operator will not just do that unless the Content is of type Brush. You have to explicitly cast it to Brush

System.Object is the type of the Content property. Through inheritance there's already an implicit conversion to the base type

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top