WPF - Border template with content

こ雲淡風輕ζ 提交于 2019-12-12 09:48:31

问题


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

<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.


回答1:


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

...

In some Resources collection:

<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 UserControl and expose certain parts of the markup as DependencyPropertys that you can data bind to from outside the control:

<Prefix:YourUserControl CustomContent="{Binding SomeDataObject}" />

Inside the control:

<ContentControl Content="{Binding CustomContent, 
    RelativeSource={RelativeSource AncestorType={x:Type Local:YourUserControl }}}" />



回答2:


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



来源:https://stackoverflow.com/questions/25666273/wpf-border-template-with-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!