2017-02-23 64 views
2

我發現我正在爲多個按鈕創建相同的Button樣式,但僅更改一個部分 - Button上使用的圖像。一個例子;將按鈕圖像設置爲以其樣式進行綁定

<Setter Property="ContentTemplate"> 
    <Setter.Value> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <Image Source="pack://application:,,,/Resources/MainWindowIcons/Staff.ico" Height="20"/> 
       <TextBlock Style="{StaticResource HoverUnderlineStyle}" Text="Staff" Margin="5,0,0,0"/> 
      </StackPanel> 
     </DataTemplate> 
    </Setter.Value> 
</Setter> 

這是員工代碼Button。如果我想添加另一個按鈕,我會複製整個樣式,但只需更改ImageSource即可。

有沒有一種方法我可以有風格,然後將其設置在Button本身 - 這意味着我不必多次複製樣式?

+0

您還不更改TextBlock的Text屬性? – Clemens

+0

試試這樣。 Praveen

+0

檢查此帖:http://stackoverflow.com/questions/34182134/wpf-how-to-pass-content-property-between-styles-and-controltemplate –

回答

1

你可以實現兩個附加屬性 - 一個用於Image源和一個文本 - 你可以在任何Button設置:

public class ButtonProperties 
{ 
    public static readonly DependencyProperty ImageSourceProperty = 
     DependencyProperty.RegisterAttached("ImageSource", typeof(Uri), typeof(ButtonProperties)); 

    public static Uri GetImageSource(Button button) 
    { 
     return (Uri)button.GetValue(ImageSourceProperty); 
    } 

    public static void SetImageSource(Button button, Uri value) 
    { 
     button.SetValue(ImageSourceProperty, value); 
    } 

    public static readonly DependencyProperty TextProperty = 
     DependencyProperty.RegisterAttached("Text", typeof(Uri), typeof(ButtonProperties)); 

    public static string GetText(Button button) 
    { 
     return (string)button.GetValue(ImageSourceProperty); 
    } 

    public static void SetText(Button button, string value) 
    { 
     button.SetValue(ImageSourceProperty, value); 
    } 
} 

然後你只需要定義一次ContentTemplate作爲一種資源,例如,在您的App.xaml:

<Application x:Class="WpfApplication1.App" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:WpfApplication1" 
      StartupUri="MainWindow.xaml"> 
    <Application.Resources> 
     <DataTemplate x:Key="dataTemplate"> 
      <StackPanel Orientation="Horizontal"> 
       <Image Source="{Binding Path=(local:ButtonProperties.ImageSource), RelativeSource={RelativeSource AncestorType=Button}}" Height="20"/> 
       <TextBlock Text="{Binding Path=(local:ButtonProperties.Text), RelativeSource={RelativeSource AncestorType=Button}}" Margin="5,0,0,0"/> 
      </StackPanel> 
     </DataTemplate> 
    </Application.Resources> 
</Application> 

用法:

<Button local:ButtonProperties.Text="Staff" 
       local:ButtonProperties.ImageSource="pack://application:,,,/Resources/MainWindowIcons/Staff.ico" 
       ContentTemplate="{StaticResource dataTemplate}" /> 
相關問題