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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:28:12  来源:igfitidea点击:

WPF - Border template with content

xmlwpfxamlbordercontentcontrol

提问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 }}}" />

回答by Maximus

Since Control does not derive from ContentControl it does not expose Content property. Take a look for more information here.

由于 Control 不是从 ContentControl 派生的,因此它不公开 Content 属性。在这里查看更多信息。