代码之家  ›  专栏  ›  技术社区  ›  Jens

静态资源的数据绑定按钮内容失败

  •  1
  • Jens  · 技术社区  · 14 年前

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

    我有

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

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

    我也尝试过 ... 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.

    问题出在哪里?我想我终于明白了……=

    2 回复  |  直到 11 年前
        1
  •  2
  •   Chris Nicol    14 年前

    我建议使用模板而不是设置内容。

    <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}" /> 
    

    高温高压

        2
  •  0
  •   Jared Thirsk    11 年前

    我通过将ContentTemplate设置为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.