2012-02-13 37 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