WPF样式设置器中的TemplateBinding是什么?

13
我在我的WPF应用程序中使用了<setter>,我需要使用TemplateBinding来评估该Setter Property的值,以在编译时进行计算,但我无法使用TemplateBinding,因为它会引发错误。
我的代码如下:
                <ControlTemplate TargetType="{x:Type srcview:ButtonView}">
                    <Button>
                        <Button.Style>
                            <Style TargetType="{x:Type Button}">
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Background" Value="{TemplateBinding Color}"></Setter>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Button.Style>
                    </Button>
                </ControlTemplate>

我该如何在样式设置器中使用TemplateBinding,或者是否有其他方法可以在编译时计算值?


1
你到底想做什么? - Vishal
你遇到了什么错误? - Rohit Vats
@Farzi 我想在setter中使用TemplateBinding。我该怎么做? - Karthi Keyan
3个回答

14

事实上,Setter 不支持 TemplateBinding。请改用以下方法:

<Setter Property="Background"
        Value="{Binding Color, RelativeSource={RelativeSource Self}}"/>

但请注意,您所引用的颜色属性必须是 brush 类型。背景是 brush,您无法将颜色绑定到 brush。


是的,我知道,但是你的代码只会在运行时评估该值,但 TemplateBinding 将在编译时评估它。我需要在编译时测试该值,那么还有其他方法可以实现吗? - Karthi Keyan
2
@karthik - 你只能在ControlTemplate内容中使用TemplateBinding,而不能在Style内容中使用。 RelativeSource是一种可行的方法。 - Rohit Vats
TemplateBinding在编译时不会评估值。所有类型的绑定都在运行时评估。这就是这个想法的优势。所以,Farzi已经问了,你想要实现什么? - gomi42

4

如果你非常希望使用TemplateBinding,那么可以反转触发器的作用。让它基于IsMouseOver为False来设置值,然后直接在按钮上使用TemplateBinding。这种方法的缺点是你需要在触发器中提供静态值。例如:

<Window x:Class="StackOverflow._20799186.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ControlTemplate x:Key="ControlAsButtonTemplate" TargetType="{x:Type ContentControl}">
            <Button x:Name="MyButton" Content="Hello World!" Background="{TemplateBinding Background}" />

            <ControlTemplate.Triggers>
                <Trigger SourceName="MyButton" Property="IsMouseOver" Value="False">
                    <Setter TargetName="MyButton" Property="Background" Value="Silver" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Window.Resources>

    <ContentControl Template="{StaticResource ControlAsButtonTemplate}" Background="Green" />
</Window>

请注意使用ControlTemplate.Triggers而不是Button.Style.Triggers。
希望这可以帮到您。

1
您可能需要在模板中定义颜色属性,才能绑定到该属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接