2012-03-31 18 views
0

我創建的App.xaml文件中的樣式按鈕變化圖像具有一些風格

<ControlTemplate x:Key="controlButtonFavourite" TargetType="{x:Type Button}"> 
      <Grid> 
       <Image x:Name="imgButtonBackground" Source="/WpfApp;component/Media%20Images/MediaNavigationButtonBackground.png" Stretch="Uniform"></Image> 
       <Image x:Name="imgNavigationButtonTypeFavourite" Source="/WpfApp;component/Media%20Images/MediaFav_White.png" Stretch="Uniform" Margin="9"/> 
      </Grid> 
      <ControlTemplate.Triggers> 
       <Trigger Property="IsFocused" Value="True"> 
        <Setter TargetName="imgNavigationButtonTypeFavourite" Property="Source" Value="/WpfApp;component/Media%20Images/MediaFav_Gold.png" /> 
       </Trigger> 
      </ControlTemplate.Triggers> 
     </ControlTemplate> 

現在我想在運行時的具體情況來改變imgNavigationButtonTypeFavourite的形象。我無法弄清楚如何改變這張圖片。請建議如何可能?

回答

2

您可以繼承Button併爲圖像路徑添加依賴項屬性。該屬性可用於ControlTemplate。按鈕的

public class ImageButton : Button 
{ 
    public static readonly DependencyProperty ImagePathProperty = 
     DependencyProperty.Register("ImagePath", typeof (string), typeof (ImageButton)); 

    public string ImagePath 
    { 
     get { return (string) GetValue(ImagePathProperty); } 
     set { SetValue(ImagePathProperty, value); } 
    } 
} 

用法:

<ImageButton x:Name="imageButton" ImagePath="..." /> 

背後使用代碼:

imageButton.ImagePath = "..."; 

使用模板:

<Setter TargetName="imgNavigationButtonTypeFavourite" Property="Source" Value="{TemplateBinding ImagePath}" /> 
+0

是的,我可以,但我想使用從我的問題中描述的App.xaml風格。那麼有沒有機會改變圖像? – Rupesh 2012-04-03 08:53:54

+0

使用我的建議,您可以在App.xaml中定義樣式,但必須在使用該控件時定義ImagePath。另一種方法是使用Triggers或VisualStates作爲控件,但不能對所有應用程序的具體情況做出反應。 – MatthiasG 2012-04-03 09:23:31