【问题标题】:Change image of button which have some style更改具有某种样式的按钮的图像
【发布时间】:2012-03-31 12:31:37
【问题描述】:

我在 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 的图像。我无法弄清楚如何更改此图像。请建议怎么可能?

【问题讨论】:

    标签: wpf button styles


    【解决方案1】:

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

    【讨论】:

    • 是的,我可以,但我想使用 App.xaml 中的样式,如我的问题中所述。那么有没有机会改变形象?
    • 根据我的建议,您可以在 App.xaml 中定义样式,但在使用控件时必须定义 ImagePaths。另一种方法是使用 Triggers 或 VisualStates 作为控件,但您无法对所有应用程序特定条件做出反应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多