2011-09-24 150 views
0

我正在研究WPF应用程序。我有一个资源字典,我在其中为ToolTip和Button编写了自定义样式。事实上,我做了两种风格的按钮。 其中之一,包括一个图像显示在buttoon内容的左侧。动态更改样式的属性

<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个按钮,我希望每个按钮都有不同的图像。 你们有什么想法吗? 谢谢!

回答

0

有许多选项,从(ab)使用属性(如Tag)继承或组成UserControl,您也可以创建attached property

最干净的很可能是虽然继承,那么你就可以创建适用于ImageSourcedependency 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

+0

哇。感谢你的回答。问题在于,我是WPF的新成员_kinda_。你能提供一个简单的例子来解决我的问题吗?这会让我的生活变得更容易 –

+0

@MihaiuAdrian:好吧,可能需要几分钟... –

+0

谢谢。我回到别的东西,直到你回答。非常感谢你! :) –