从子自定义控件的控件模板绑定到父用户控件'

本文关键字:控件 用户 自定义控件 绑定 | 更新日期: 2023-09-27 18:13:08

我有一个父UserControl (ParentUserControl),它由一个子CustomControl (ChildCustomControl)组成。在我的子自定义控件的控件模板中,我想绑定到代码隐藏文件ParentUserControl.xaml.cs中定义的属性。如果可以这样做,它的语法是什么?

从子自定义控件的控件模板绑定到父用户控件'

您可以使用父控件的名称轻松地引用它。在这种情况下,Xaml看起来像这样:

<ParentUserControl Name="ParentControl">
  <ChildUserControl>
    <ChildUserControl.Template>
      <ControlTemplate TargetType="{x:Type ChildUserControl}">
        <Grid Background={Binding Path=Background, ElementName=ParentControl}>
...

可以正常使用TemplateBinding…例:{TemplateBinding propName}

是,您可以使用以下绑定将子控件的控件模板中的属性与父控件的属性绑定:

PropertyName = "{Binding 
        Source={RelativeSource Mode=FindAncestor, 
        AncestorType=ParentUserControl},
    Path=ParentPropertyName}"

这里PropertyName将是子控件的控件模板中的属性,ParentUserControl将是父用户控件的名称,ParentPropertyName将是父控件的属性。