简体   繁体   中英

Editing Template Binding in control templates

I created a ControlTemplate like this:

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

and now i want to be able to edit both textblocks, how do i do it? I tried something like this and other variations but it didn't work:

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

A ContentControl has no c1 and c2 properties. If you create a custom control and define these as dependency properties, it would work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM