【问题标题】:Changing Property of a Style Dynamically动态更改样式的属性
【发布时间】:2011-09-24 15:49:26
【问题描述】:

我正在开发一个 WPF 应用程序。我有一个资源字典,我在其中为工具提示和按钮编写了自定义样式。实际上,对于按钮,我制作了两种样式。 其中之一,包括一个图像出现在按钮内容的左侧。

<Style x:Key="ButtonImageStyle" TargetType="{x:Type Button}">
     ........
   <TextBlock Margin="5.25,2.417,5.583,5.25" Foreground = White />
   <Image x:Name="ButtonImage" Source="/MyProject;component/Images/icoMainMenu01.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="-100,0,0,0" Width="16" Height="16"/>
   .... </Style

现在,在 MainWindow.xaml 我有以下内容:

<Button Style="{DynamicResource ButtonImageStyle}" x:Name="JustButton" Click="JustButton_Click" Height="50" ToolTip="Press for 1" Content="1" Margin="310,282,400,238"  />

我希望能够更改该图像。我将有 8 个按钮,我希望每个按钮都有与之关联的不同图像。 你们有什么想法吗? 谢谢!

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    有多种选择,从(ab)使用Tag 之类的属性到UserControl 中的子类化或组合,您还可以创建attached property

    不过,最干净的可能是子类化,然后您可以为要使用的ImageSource 创建一个新的dependency property,然后您可以使用TemplateBinding 在默认模板中绑定它。

    要进行子类化,您可以使用 VS,从新项目中选择 Custom Control (WPF),这应该创建一个类文件并将基本样式添加到主题资源字典中,该字典通常位于 Themes/Generic.xaml 中。这个类看起来像这样:

    //<Usings>
    
    namespace Test.Controls
    {
        public class ImageButton : Button
        {
            public static readonly DependencyProperty ImageProperty =
                DependencyProperty.Register("Image", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null));
            public ImageSource Image
            {
                get { return (ImageSource)GetValue(ImageProperty); }
                set { SetValue(ImageProperty, value); }
            }
        }
    }
    

    现在主题会更复杂,您只需复制一个按钮的default templates 并将其粘贴到默认样式中即可。然后你只需要在某个地方添加你的图像,但使用这个绑定:

    <Image Source="{TemplateBinding Image}" .../>
    

    当您使用此控件时,您将不再需要引用样式,因为一切都是默认样式,现在有一个图像属性:

    <controls:ImageButton Content="Lorem Ipsum"
                          Image="Img.png"/>
    

    (要使用Tag,您只需使用普通按钮并使用 TemplateBinding 到标签并将按钮的标签设置为 URL)


    我忘了提到另一种使用动态资源的可能性,它有点冗长但非常简单,请参阅我的this answer 示例。

    【讨论】:

    • 哇。感谢你的回答。问题是我有点 WPF 新手。您能否提供一个附加到我的问题的单个简单示例?这会让我的生活更轻松
    • 谢谢。在你回答之前,我传递给别的东西。非常感谢你! :)
    • @MihaiuAdrian:添加了一个示例,我最终没有再次使其独立,对此我很抱歉,但我不想复制整个默认按钮模板。
    • 感谢一百万!我会尝试一切,直到我成功为止。谢谢!祝一切顺利 ! :D
    • 所以我查看了 详细但非常简单 示例,我花了 2 分钟来调整我的代码以适应您在那里回答的内容。非常感谢你。效果很棒! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 2012-04-25
    • 2013-03-30
    相关资源
    最近更新 更多