我在我的wpf应用程序中使用<setter>
,我需要使用TemplateBinding为该setter属性在编译时评估该值,但我不能使用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
或者是否有其他方法可以在编译时评估该值?
答案 0 :(得分:10)
确实,setter不支持TemplateBinding。试试这个:
<Setter Property="Background"
Value="{Binding Color, RelativeSource={RelativeSource Self}}"/>
但请注意,您所引用的颜色属性必须是brush类型。背景是画笔,您无法将颜色绑定到画笔。
答案 1 :(得分:3)
如果您绝对使用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。
我希望这会有所帮助。
答案 2 :(得分:1)
您可能需要在模板中定义Color属性才能绑定到该属性。