在控制模板中编辑模板绑定

时间:2018-11-07 14:29:38

标签: c# wpf controltemplate

我这样创建了一个ControlTemplate

<ControlTemplate x:Key="FieldTemplate" TargetType="ContentControl">
  <Border Background="LightGray" >
    <DockPanel >
      <TextBlock DockPanel.Dock="Left" Text="{TemplateBinding c1}" />
      <TextBlock DockPanel.Dock="Left" Text="{TemplateBinding c2}" />
      <TextBox />
    </DockPanel>
  </Border>
</ControlTemplate>

现在我希望能够编辑两个文本块,我该怎么做? 我尝试了类似的方法以及其他变体,但是没有用:

<ContentControl c1="hello" c2="olleh" 
       Template="{StaticResource FieldTemplate}" x:Name="NameControl"/>

1 个答案:

答案 0 :(得分:0)

ContentControl没有c1c2属性。如果创建自定义控件并将其定义为依赖项属性,它将起作用:

public class MyControl : ContentControl
{
    public string C1
    {
        get { return (string)GetValue(C1Property); }
        set { SetValue(C1Property, value); }
    }
    public static readonly DependencyProperty C1Property = DependencyProperty.Register(nameof(C1), typeof(string), typeof(MyControl));

    public string C2
    {
        get { return (string)GetValue(C2Property); }
        set { SetValue(C2Property, value); }
    }
    public static readonly DependencyProperty C2Property = DependencyProperty.Register(nameof(C2), typeof(string), typeof(MyControl));
}

XAML:

<ControlTemplate x:Key="FieldTemplate" TargetType="local:MyControl">
    <Border Background="LightGray" >
        <DockPanel >
            <TextBlock DockPanel.Dock="Left" Text="{TemplateBinding C1}" />
            <TextBlock DockPanel.Dock="Left" Text="{TemplateBinding C2}" />
            <TextBox />
        </DockPanel>
    </Border>
</ControlTemplate>
...
<local:MyControl C1="hello" C2="olleh" Template="{StaticResource FieldTemplate}" x:Name="NameControl"/>