dev*_*xer 20 wpf xaml styles templatebinding
我正在尝试这样做......
<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>
Run Code Online (Sandbox Code Playgroud)
...但我收到错误: 'Padding' member is not valid because it does not have a qualifying type name.
我如何提供"合格类型名称"?
注意:我试图这样做的原因是,我想在一系列类似的ControlTemplates中包含相同的Border.
谢谢.
编辑:
好吧,我试过这个......
<Setter
Property="Padding"
Value="{TemplateBinding GridViewColumnHeader.Padding}" />
Run Code Online (Sandbox Code Playgroud)
......它实际编译了,但是当我运行应用程序时,我得到了XamlParseException:
Cannot convert the value in attribute 'Value' to object of type ''.
我想,也许有资格Padding与GridViewColumnHeader(这是我想用这种风格与控件模板)的工作,但没有骰子.
编辑2:
那么,根据文档TemplateBinding,它说:
将控件模板中的属性值链接为模板化控件上某些其他公开属性的值.
所以听起来我正在尝试做的事情显然是不可能的.我真的希望能够为我的控件模板中的某些控件创建可重用的样式,但我想模板绑定不能包含在这些样式中.
Sha*_*ney 36
这适用于您正在模板控件并且您希望将该控件的属性值绑定到模板内不同控件的属性的情况.在你的情况下,你是模板化的东西(称之为MyControl),该模板将包含一个边框,其Padding应绑定到MyControl的填充.
从MSDN文档:
TemplateBinding是模板场景的绑定的优化形式,类似于使用{Binding RelativeSource = {RelativeSource TemplatedParent}}构造的Binding.
无论出于何种原因,将TemplatedParent指定为绑定的源似乎在样式设置器中不起作用.为了解决这个问题,您可以将相对父项指定为您正在模板化的控件的AncestorType(有效地找到TemplatedParent,前提是您没有在MyControl模板中嵌入其他MyControl).
当我尝试自定义模板一个Button控件时,我使用了这个解决方案,其中Button的(String)内容需要绑定到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>
Run Code Online (Sandbox Code Playgroud)
该{TemplateBinding ...}快捷方式在 Setter 中不可用。
但没有人会阻止您使用完整的详细版本,例如:
Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Padding}"。