Tuesday, January 22, 2013

Databinding Button Content to a static resource fails

Databinding Button Content to a static resource fails

I am trying to design a set of icons in a Silverlight 4 User Control's ressources, and then display these on a button.

I have

<UserControl.Resources>             <Rectangle x:Key="Icon1" Fill="Black" Width="10" Height="10" />             </UserControl.Resources> 

and

<Button x:Name="Button1"         Width="50" Height="50"                                 Content="{Binding Source={StaticResource Icon1}}" />  

I also tried ... Content="{StaticResource Icon1}". Both show fine in the XAML Designer of VS 2010, but fail when I try to run it with a XAMLParseException. The first one complains about the argument not falling into the expected range, the second one simply says "Failed to assign property". Copying the Rectangle into the Buttons content directly works fine.

Where is the problem? I thought I finally understood this.. =/

Answers & Comments...

Answer: 1

I would suggest using a template instead of setting the content anyway.

<ControlTemplate     x:Key="IconTemplate">        <Rectangle x:Key="Icon1" Fill="Black" Width="10" Height="10" />    </ControlTemplate>  <Style x:Key="IconStyle" TargetType="Button">        <Setter Property="Template" Value="{StaticResource IconTemplate}"/> </Style>  <Button x:Name="Button1"         Width="50" Height="50"                                 Style="{StaticResource IconStyle}" />  

HTH

by : Chris Nicolhttp://stackoverflow.com/users/79910

Answer: 2

I accomplished this by setting the ContentTemplate to a DataTemplate:

<UserControl.Resources>             <DataTemplate x:Key="Icon1">         <Rectangle Fill="Black" Width="10" Height="10" />                 </DataTemplate> </UserControl.Resources> 

Button:

<Button x:Name="Button1"         Width="50" Height="50"                                 ContentTemplate="{StaticResource Icon1}" />  

Setting the Template on the Button works too, but I believe you have to replace the entire template for the control. This approach lets you keep the existing control template.

by : Jared Thirskhttp://stackoverflow.com/users/208304




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog