更改具有某种样式的按钮的图像



>我在 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>

现在我想在特定条件下在运行时更改 imgNavigationButtonTypeFavorite 的图像。 我无法弄清楚如何更改此图像。请建议怎么可能?

可以从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}" />

相关内容

  • 没有找到相关文章