2011-09-24 153 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

謝謝。我回到別的東西,直到你回答。非常感謝你! :) –