【问题标题】:Setting a Button Image to Binding in its Style将按钮图像设置为其样式绑定
【发布时间】:2017-02-24 00:41:19
【问题描述】:

我发现我正在为多个按钮创建相同的 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 本身上进行设置 - 这意味着我不必多次复制样式?

【问题讨论】:

标签: c# wpf xaml


【解决方案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}" />

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 2017-10-08
    • 2011-02-15
    • 2014-11-09
    • 2011-03-08
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2010-12-31
    相关资源
    最近更新 更多