在自定义用户控件中引用来自父 window 的控件

Reference a control from parent window in a custom user control

我正在尝试创建一个可重复使用的弹出式用户控件。它需要是一个用户控件,因为它需要包含一个按钮和一个超链接,单击时需要隐藏代码。 我想将弹出窗口的 PlacementTarget 设置为父级 window 中的控件(例如按钮),并希望能够传入控件名称,以便弹出窗口将在相关控件旁边打开。 我尝试了以下方法,但它不起作用。

用户控制:

<UserControl
  x:Class="SampleTestProject.WPF.VrtContactUserTooltip"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Name="parent">
  <Grid>
    <Popup
    Name="ContactTooltip"
    PlacementTarget="{Binding Path=Target, ElementName=parent}"
    DataContext="{Binding Path=Contact}"/>
    </Grid>
</UserControl>

用户控制的隐藏代码:

 public partial class VrtContactUserTooltip : UserControl
  {
public VrtContactUserTooltip()
{
  InitializeComponent();
}

#region Properties

#region Target

/// <summary>
/// Gets or sets the Target of the tooltip
/// </summary>
public string Target
{
  get { return (string)GetValue(TargetProperty); }
  set { SetValue(TargetProperty, value); }
}

/// <summary>
/// Identified the Target dependency property
/// </summary>
public static readonly DependencyProperty TargetProperty =
  DependencyProperty.Register("Target", typeof(string),
    typeof(VrtContactUserTooltip), new PropertyMetadata(""));

#endregion

#region Contact

/// <summary>
/// Gets or sets the Contact of the tooltip
/// </summary>
public Contact Contact
{
  get { return (Contact)GetValue(ContactProperty); }
  set { SetValue(ContactProperty, value); }
}

/// <summary>
/// Identified the Contact dependency property
/// </summary>
public static readonly DependencyProperty ContactProperty =
  DependencyProperty.Register("Contact", typeof(Contact),
    typeof(VrtContactUserTooltip), new PropertyMetadata(null));

#endregion
#endregion
  }
}

正在使用用户控件的位置:

 <Button
    x:Name="PopupButton3" />
  <wpf:VrtContactUserTooltip
    Target="{Binding Source={x:Reference PopupButton3}}"
    Contact="{Binding Path=Contact}"/>

是否可以这样做(即将控件名称从父控件传递到用户控件并绑定到它)?

参见:

我认为您也可以不执行查找祖先,而只是显式传入父 control/window 作为子控件的数据上下文并绑定到它。

设计明智:这取决于您重用控件的可能性。子用户控件是不是要在常见场景中重复使用和重复使用的东西?如果是这样,可能可以在 XAML 中执行,但我处理它的方式是定义一个控件希望其父级实现的接口,以及一个将实现该接口的东西作为参数的构造函数.在 C# 方面,我将父 属性 转换为 "IHaveWhatINeed",我需要在其中使用父控件属性。这将使父控件和子控件之间的耦合变得明确,并将耦合隔离到子控件依赖于父控件的 properties/functions 的特定子集。

private IWhatINeed data;
public ChildControl( IWhatINeed requiredData )
{ ... }

我最终在使用用户控件的 window 的构造函数中设置了 PlacementTarget。 我将以下行放在父 window 的构造函数中:

ContactPopup3.ContactTooltip.PlacementTarget = PopupButton3;

这并不理想(因为每次使用用户控件时都需要在后面的代码中设置),但它解决了问题。