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
Converter

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">
<Rectangle.Fill>
<VisualBrush Stretch="Fill" Visual="{StaticResource defalt_icon}" />
</Rectangle.Fill>
</Rectangle>
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">
<Rectangle.Fill>
<VisualBrush Stretch="Fill">
<VisualBrush.Visual>
<MultiBinding Converter="{StaticResource IconNameConverter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource
AncestorType=FrameworkElement}"/>
<Binding Path="IconName"/>
</MultiBinding.Bindings>
</MultiBinding>
</VisualBrush.Visual>
</VisualBrush>
</Rectangle.Fill>
</Rectangle>
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 =
(FrameworkElement)targetElement.TryFindResource(iconName);
if (newIcon == null)
newIcon =
(FrameworkElement)targetElement.TryFindResource("appbar_page_question");
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