在控件模板中编辑模板绑定
Editing Template Binding in control templates
我创建了一个 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"/>
A ContentControl
没有 c1
和 c2
属性。如果您创建一个自定义控件并将它们定义为依赖属性,它将起作用:
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"/>
我创建了一个 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"/>
A ContentControl
没有 c1
和 c2
属性。如果您创建一个自定义控件并将它们定义为依赖属性,它将起作用:
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"/>