我正在创建自己的控件,我想知道绑定下面的textblock文本属性的最佳方法,我将contentpresenter设置为绑定到内容,如何设置textblock文本值?
<Style TargetType="ctrl:Selection">
<Setter Property="Width" Value="200" />
<Setter Property="Height" Value="100" />
<Setter Property="Background" Value="Lavender" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ctrl:Selection">
<Grid x:Name="RootElement">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Rectangle Grid.Row="0" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Fill="{TemplateBinding Background}" Stroke="black" RadiusX="16" RadiusY="16" />
<TextBlock Grid.Row="0" Text="How do i bind this?" x:Name="HeaderText" HorizontalAlignment="Center" VerticalAlignment="Center" />
<ContentPresenter Grid.Row="1" x:Name="BodyContent" Content="{TemplateBinding Content}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
public class Selection : ContentControl {
public Selection() {
this.DefaultStyleKey = typeof(Selection);
}
}
答案 0 :(得分:3)
您可以在控件类中注册属性,类似这样......
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(Selection), new PropertyMetadata(""));
public string Text {
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}