在自定义用户控件中从父窗口引用控件

时间:2018-08-26 11:45:05

标签: c# wpf xaml user-controls

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

用户控制:

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

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

2 个答案:

答案 0 :(得分:0)

请参阅:https://stackoverflow.com/a/1127964/1462330

我认为您也可以做一个查找祖先,而不是直接将父控件/窗口作为子控件的数据上下文传递并绑定到它。

明智的设计:这取决于您重用控件的可能性。子用户控件是否可以在常见情况下重用?如果是这样,可能会在XAML中完成,但是我要处理的方式是定义一个控件希望控件的父控件实现的接口,以及一个将实现该接口的参数作为参数的构造函数。在C#端,我将父属性转换为需要使用父控件属性的“ IHaveWhatINeed”。这样可以明确父控件和子控件之间的耦合,并将耦合与子控件所依赖的特定属性/函数子集隔离开。

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

答案 1 :(得分:0)

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

ContactPopup3.ContactTooltip.PlacementTarget = PopupButton3;

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

相关问题