问题
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 DependencyProperty
s 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