将按钮图像设置为其样式中的绑定

时间:2017-02-23 12:13:33

标签: c# wpf xaml

我发现我为多个按钮创建了相同的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的代码。如果我想添加另一个按钮,我会复制整个样式,但只需更改Source的{​​{1}}。

我是否可以使用样式然后在Image本身上设置它 - 这意味着我不必多次复制样式?

1 个答案:

答案 0 :(得分: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}" />