Wednesday, 18 September 2013

WPF Binding from strings to Canvas objects in a ResourceDictionary using Converter

WPF Binding from strings to Canvas objects in a ResourceDictionary using

I have a ResourceDictionary made up of icons/Canvas objects drawn with
Paths. My ViewModel includes a string property (IconName) that contains a
string matching one of the entries in the ResourceDictionary. I developed
a MultiBinding (IMultiValueConverter) that takes the string, and a
FrameworkElement and does a resource lookup, returning the resource
matching the name. Before getting to this point, I stubbed my View
explicitly with the following:
<Rectangle Width="10" Height="10" Margin="0,0,10,0">
<VisualBrush Stretch="Fill" Visual="{StaticResource defalt_icon}" />
This renders correctly. However, when I switch out to the following,
nothing is rendered in the Rectangle.
<Rectangle Width="10" Height="10" Margin="0,0,10,0">
<VisualBrush Stretch="Fill">
<MultiBinding Converter="{StaticResource IconNameConverter}">
<Binding RelativeSource="{RelativeSource
<Binding Path="IconName"/>
My converter (show below) is being called, and does find the Canvas object
and returns it (viewing the object in the debugger I can see that Canvas
has a Path child that has the right Data member filled in).
public class IconNameConverter : IMultiValueConverter
public object Convert(object[] values, Type targetType, object
parameter, System.Globalization.CultureInfo culture)
FrameworkElement targetElement = values[0] as FrameworkElement;
string iconName = values[1] as string;
if (iconName == null)
return null;
FrameworkElement newIcon =
if (newIcon == null)
newIcon =
return newIcon;
public object[] ConvertBack(object value, Type[] targetTypes, object
parameter, System.Globalization.CultureInfo culture)
throw new NotImplementedException();
Any ideas why the canvas isn't showing up?

No comments:

Post a Comment