我的WPF样式设置器可以使用TemplateBinding吗?
我正试着做这样的事情我的WPF样式设置器可以使用TemplateBinding吗?,wpf,xaml,styles,templatebinding,Wpf,Xaml,Styles,Templatebinding,我正试着做这样的事情 <Style x:Key="MyBorderStyle" TargetType="Border"> <Setter Property="BorderBrush" Value="{StaticResource MyBorderBrush}" /> <Setter Property="Background" Value="{StaticResource
<Style
x:Key="MyBorderStyle"
TargetType="Border">
<Setter
Property="BorderBrush"
Value="{StaticResource MyBorderBrush}" />
<Setter
Property="Background"
Value="{StaticResource MyBackgroundBrush}" />
<Setter
Property="Padding"
Value="{TemplateBinding Padding}" />
</Style>
…它实际上已编译,但当我运行应用程序时,我得到了一个XamlParseException
:
无法将属性“value”中的值转换为“”类型的对象。
我想也许用GridViewColumnHeader
限定Padding
(这是我想要使用这种样式的控制模板)会起作用,但没有骰子
编辑2:
根据TemplateBinding
的文档,它说:
将控件模板中某个属性的值链接为模板化控件上某个其他公开属性的值
所以听起来我想做的是完全不可能的。我确实希望能够为控件模板中的某些控件创建可重用的样式,但我猜这些样式中不能包含模板绑定。只需在属性前面加上类型名,即可对其进行限定。例如,
Border.Padding
而不是Padding
但是,我不确定这对您的场景是否有意义<代码>模板绑定在控件模板内使用。这适用于正在模板化控件并且希望将该控件的属性值绑定到模板内其他控件的属性的情况。在您的例子中,您正在模板化某个东西(称之为MyControl),该模板将包括一个边框,其填充应绑定到MyControl的填充 发件人: TemplateBinding是模板场景中绑定的优化形式,类似于使用{Binding RelativeSource={RelativeSource TemplatedParent}构造的绑定 无论出于何种原因,将TemplatedParent指定为绑定的源似乎在样式设置器中不起作用。为了避免这种情况,您可以将相对父级指定为正在模板化的控件的AncestorType(如果您没有在MyControl模板中嵌入其他MyControl,则可以有效地查找TemplatedParent) 我在尝试自定义按钮控件模板时使用了此解决方案,其中按钮的(字符串)内容需要绑定到按钮的ControlTemplate中TextBlock的Text属性。下面是代码的样子:
<StackPanel>
<StackPanel.Resources>
<ControlTemplate x:Key="BarButton" TargetType="{x:Type Button}">
<ControlTemplate.Resources>
<Style TargetType="TextBlock" x:Key="ButtonLabel">
<Setter Property="Text" Value="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type Button}} }" />
</Style>
</ControlTemplate.Resources>
<Grid>
<!-- Other controls here -->
<TextBlock Name="LabelText" Style="{StaticResource ButtonLabel}" />
</Grid>
</ControlTemplate>
</StackPanel.Resources>
<Button Width="100" Content="Label Text Here" Template="{StaticResource BarButton}" />
</StackPanel>
当然可以
{TemplateBinding…}
快捷方式在Setter中不可用
但是没有人会阻止你使用完整的详细版本
例如:
Value=“{Binding RelativeSource={RelativeSource TemplatedParent},Path=Padding}”
谢谢,@Kent。你的回答给了我一个尝试的想法(见上面我的编辑),但没有成功。TemplateBinding
s只能在ControlTemplate中使用……只要我能说服解析器我打算只在ControlTemplate中使用这种样式……或者,使用{Binding RelativeSource={RelativeSource TemplatedParent},Path=…}
<StackPanel>
<StackPanel.Resources>
<ControlTemplate x:Key="BarButton" TargetType="{x:Type Button}">
<ControlTemplate.Resources>
<Style TargetType="TextBlock" x:Key="ButtonLabel">
<Setter Property="Text" Value="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type Button}} }" />
</Style>
</ControlTemplate.Resources>
<Grid>
<!-- Other controls here -->
<TextBlock Name="LabelText" Style="{StaticResource ButtonLabel}" />
</Grid>
</ControlTemplate>
</StackPanel.Resources>
<Button Width="100" Content="Label Text Here" Template="{StaticResource BarButton}" />
</StackPanel>