我在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 的图像。我无法弄清楚如何更改此图像。请建议如何实现?
答案 0 :(得分: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}" />