2012-02-13 89 views
0

我用this MSDN tutorial为我的窗口的所有Button控件创建了一个眼睛糖果外观,并且工作正常。为了使它更具可重用性,我尝试将所有内容放在UserControl中:我创建了一个ImageButton UC,然后将所有<Style><Window.Resources>封装到<UserControl.Resources>UserControl中的参数化风格?

然后,我改变了我的Button实例在XAML,从:

<Button Tag="Face.jpg" Content="Foo" />

要:

<uc:ImageButton Tag="Face.jpg" Content="Foo" />

而且款式停止被应用。

这里是UC代码:

<UserControl x:Class="GDTI.UI.Main.View.UserControls.ImageButton" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300"> 

<UserControl.Resources> 
    <Style TargetType="Button"> 
     <Setter Property="MaxWidth" Value="250" /> 
     <Setter Property="Margin" Value="5" /> 
     <Setter Property="FontWeight" Value="Bold" /> 
     <Setter Property="Foreground" Value="White" /> 

     <Setter Property="Background" > 
      <Setter.Value> 
       <SolidColorBrush Color="Orange" Opacity="0.4" /> 
      </Setter.Value> 
     </Setter> 

     <Setter Property="ContentTemplate"> 
      <Setter.Value> 
       <DataTemplate > 
        <StackPanel> 
         <Image Source="{Binding Tag, 
          RelativeSource={RelativeSource 
               FindAncestor, 
               AncestorType='Button'}}" /> 
         <TextBlock Margin="10" 
      HorizontalAlignment="Center" 
      Text="{Binding Content, 
        RelativeSource={RelativeSource 
             FindAncestor, 
             AncestorType='Button'}}" /> 
        </StackPanel> 
       </DataTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

</UserControl.Resources> 

<Button/> 

我缺少什么?

谢谢!

+0

Gaaahhh!你有自定义的用户控件,你仍然使用'Tag'属性? (也很难说明问题出在你没有发布的代码中) – 2012-02-13 17:19:46

+0

下一步是避免使用'Tag'属性,这就是为什么我要使用UCs ...现在发布代码 – 2012-02-13 17:35:07

回答

0

按钮上的按钮样式目标属性中的绑定,它不再具有设置的属性。您需要转发那些到UserControl如果你想保留风格的完整性:

<!-- Inside UserControl declaration --> 
<Button Content="{Binding Caption, RelativeSource={RelativeSource AncestorType=UserControl}}" 
     Tag="{Binding ImageSource, RelativeSource={RelativeSource AncestorType=UserControl}}"/> 

CaptionImageSource应该是新dependency properties在用户控件定义(代码隐藏)。

,你永远无法绑定到 ContentUserControl(因此 Caption属性)

注意,这里的Button本身UserControlContent

或者,您可以通过将AncestorType更改为UserControl来绕过Button,直接更改样式中的定位。绑定超出模板控制不是很好的做法,但你仍然在UserControl,所以它是可原谅的。

无论哪种方式,这是有点hacky,而不是从Button继承。

+0

谢谢朋友,你的解决方案似乎工作 – 2012-02-14 10:13:53

+0

@ silentman.it:很高兴听到这一点。如果这足以回答你的问题,你可以[接受](http://meta.stackexchange.com/questions/5234/)的答案。 – 2012-02-14 13:24:47