一些元素的WPF XAML更改样式模板属性 [英] WPF XAML Change Style Template Property for Some Elements

查看:51
本文介绍了一些元素的WPF XAML更改样式模板属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF应用程序中,我有一种用于按钮的样式:

In a WPF application I have a style used for buttons:

<Style TargetType="Button" x:Key="ButtonEllipse">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <StackPanel Orientation="Vertical">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0 0 0 10"/>
                    <Image x:Name="ButtonImage" HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="None" Source="/MyProject;component/Images/ButtonEllipse.png"/>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

对于大多数可以的按钮,但是对于一个特定的实例,我想使用相同的模板,但是将图像更改为ButtonEllipseNew.png(这是视图模型属性的值).该按钮的定义如下:

For most buttons that is OK but for one specific instance I want to use the same template but change the image to ButtonEllipseNew.png (which is the value of a view model property). The button is defined like this:

<Button Content="Test" Style="{StaticResource ButtonEllipse}">
</Button>

如何仅为该特定按钮更改模板中图像源的值?我想将源绑定到视图模型中的属性.

How can I change the value of the image source in the template only for this specific button? I want to bind the source to a property in the view model.

推荐答案

我将编写一个类似于以下内容的自定义控件:

I would write a custom control that looks something like this:

internal class IconButton : Button
{
    public ImageSource Source
    {
        get { return (ImageSource)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }

    public static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register("Source", typeof(ImageSource), typeof(IconButton), new PropertyMetadata(null));

}

然后编辑您的样式以适应它:

Then edit your style to accommodate it:

<Style TargetType="{x:Type location:IconButton}" x:Key="ButtonEllipse">
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type location:IconButton}">
            <StackPanel Orientation="Vertical">
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0 0 0 10"/>
                <Image x:Name="ButtonImage" HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="None" Source="{TemplateBinding Source"/>
            </StackPanel>
        </ControlTemplate>
    </Setter.Value>
</Setter>

位置是xaml定义的名称空间,其中放置IconButton类.

Where location is a xaml-defined namespace where the IconButton class is placed.

然后只需设置按钮的 Source 属性.您也可以使用Source属性来设置默认值.

Then just set the Source property of your button. You can mess around with the Source property to set a default as well.

这篇关于一些元素的WPF XAML更改样式模板属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆