WPF - 带内容的边框模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25666273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF - Border template with content
提问by user3154369
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>
How can I change content of the control in wpf? I've tried something like
如何更改 wpf 中控件的内容?我试过类似的东西
<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.
但是当我这样做时,它告诉我无法识别或找不到该属性内容。
回答by Sheridan
You need to use the ContentControlon its own to do what you want... to be clear, a ContentControlelement has nothing to do with a Controlelement. It is used to display a data object and optionally apply a DataTemplateto the object. The DataTemplateis that part that you can customise:
您需要ContentControl单独使用来做您想做的事……要清楚,ContentControl元素与Control元素无关。它用于显示数据对象并可选择将 aDataTemplate应用于该对象。这DataTemplate是您可以自定义的部分:
<ContentControl Content="{Binding SomeDataObject}"
ContentTemplate="{StaticResource SomeDataObjectTemplate}" />
...
...
In some Resourcescollection:
在一些Resources集合中:
<DataTemplate x:Key="SomeDataObjectTemplate" DataType="{x:Type Prefix:SomeDataObject}">
<Grid>
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="3" />
<TextBlock Text="{Binding}" />
</Grid>
</DataTemplate>
Your only other alternative is to declare a UserControland expose certain parts of the markup as DependencyPropertys that you can data bind to from outside the control:
您唯一的其他选择是声明 aUserControl并将标记的某些部分公开为DependencyProperty您可以从控件外部进行数据绑定的 s :
<Prefix:YourUserControl CustomContent="{Binding SomeDataObject}" />
Inside the control:
控件内部:
<ContentControl Content="{Binding CustomContent,
RelativeSource={RelativeSource AncestorType={x:Type Local:YourUserControl }}}" />

