2012-03-31 17 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