WPF-带有内容的边框模板 [英] WPF - Border template with content
问题描述
假设我具有以下控制模板:
Let's assume I have the following control template:
<ControlTemplate x:Key="Test">
<Grid>
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" Width="33" Height="33" CornerRadius="3"/>
<ContentControl Content="{TemplateBinding Property=ContentControl.Content}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</ControlTemplate>
如何在wpf中更改控件的内容?我已经尝试过类似
How can I change content of the control in wpf? I've tried something like
<Control Template="{StaticResource Test}" BorderBrush="Black" Content="aa"></Control>
但是当我这样做时,它说我无法识别或找不到属性内容。
But when I do so I it says me that the property content is not recognized or it is not found.
推荐答案
您需要自行使用 ContentControl
您想要...要清楚一点, ContentControl
元素与 Control
元素无关。它用于显示数据对象,还可以选择将 DataTemplate
应用于该对象。 DataTemplate
是您可以自定义的部分:
You need to use the ContentControl
on its own to do what you want... to be clear, a ContentControl
element has nothing to do with a Control
element. It is used to display a data object and optionally apply a DataTemplate
to the object. The DataTemplate
is that part that you can customise:
<ContentControl Content="{Binding SomeDataObject}"
ContentTemplate="{StaticResource SomeDataObjectTemplate}" />
...
在某些资源
集合:
<DataTemplate x:Key="SomeDataObjectTemplate" DataType="{x:Type Prefix:SomeDataObject}">
<Grid>
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="3" />
<TextBlock Text="{Binding}" />
</Grid>
</DataTemplate>
您唯一的其他选择是声明 UserControl
并将标记的某些部分显示为 DependencyProperty
s,您可以从控件外部将数据绑定到这些内容:
Your only other alternative is to declare a UserControl
and expose certain parts of the markup as DependencyProperty
s that you can data bind to from outside the control:
<Prefix:YourUserControl CustomContent="{Binding SomeDataObject}" />
在控件内部:
<ContentControl Content="{Binding CustomContent,
RelativeSource={RelativeSource AncestorType={x:Type Local:YourUserControl }}}" />
这篇关于WPF-带有内容的边框模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!