使用 ElementName 将 XAML 元素绑定到用户控件



我的页面中有以下 XAML 元素的方案和层次结构:

<Page> ....
 <StackPanel> ...
     <Grid> ....
       <StackPanel>
         <uc:MyUserControl
             ReferencedButton={Binding ElementName=RightButton} />
              <Button x:Name="RightButton" Click="{x:Bind ViewModel.OpenFlyout}" Content="Clickme" />
       </StackPanel>
  ......

然后是"我的用户控件"中的代码

    public UIElement ReferencedButton
    {
        get { return (UIElement)GetValue(ReferencedButtonProperty); }
        set { SetValue(ReferencedButtonProperty, value); }
    }
    public static readonly DependencyProperty ReferencedButtonProperty =
        DependencyProperty.Register(nameof(ReferencedButton), typeof(UIElement), typeof(MyUserControl), null);

到目前为止一切顺利,但是我期望在我的代码隐藏中,"ReferencedButton"属性将填充对"RightButton"按钮的引用。但是,它始终返回 null。

我什至尝试过:

{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, ElementName=RightButton}

我知道可以绑定元素,因为我从 DevExpress 组件中获得了示例,但仍然没有任何成功。

我正在遵循以下文档中的建议/规则:

绑定元素名称

XAML 名称范围

p.s:我知道我可以在代码后面传递对按钮的引用,但我想通过 XAML 本身执行此操作。

事实证明,我需要使用PropertyChangedCallback来使其工作。所以解决方案如下:

public static readonly DependencyProperty ReferencedButtonProperty=
        DependencyProperty.Register(nameof(ReferencedButton),
                typeof(UIElement),
                typeof(MyUserControl),
                new PropertyMetadata(default(UIElement),
                new PropertyChangedCallback(PlacementCallBack)));

在我的控件背后的代码中,我可以通过实现 PlacementCallBack 来访问和设置值,如下所示:

        public static void PlacementCallBack(object sender, DependencyPropertyChangedEventArgs e)
        {
            var myuserControl = sender as MyUserControl;
            myuserControl.ReferencedButton = e.NewValue as UIElement;
        }

对象DependencyPropertyChangedEventArgs包含两个属性 NewValue 和 OldValue,它们保存前一个对象集的旧值和新值。

最新更新