1

我有 MyUserControl 类,它扩展了 UserControl,带有一个参数:

namespace MyNameSpace
{
    public partial class MyUserControl: UserControl
    {
        public MyUserControl()
        {
            InitializeComponent();
        }

        private Control _owner;
        public Control Owner
        {
            set { _owner = value; }
            get { return _owner; }
        }
    }
}

例如,如何将 XAML 中的 Grid 作为该参数传递?

<Window x:Class="MyNameSpace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:my="clr-namespace:MyNameSpace">
    <Grid x:Name="grid1">
        <my:MyUserControl x:Name="myUserControl1" Parent="*grid1?*" />
    </Grid>
</Window>
4

2 回答 2

3

您需要将Owner属性实现为DependencyProperty。这是用户控件所需的代码:

public static readonly DependencyProperty OwnerProperty =
    DependencyProperty.Register("Owner", typeof(Control), typeof(MyUserControl), 
    new FrameworkPropertyMetadata(null, OnOwnerPropertyChanged)
);

private static void OnOwnerPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
    ((MyUserControl)source).Owner = (Control)e.NewValue;
}

public Control Owner
{
    set { SetValue(OwnerProperty, value); }
    get { return (Control)GetValue(OwnerProperty); }
}

然后在 XAML 中,您将能够按预期设置属性:

<Button x:Name="Button1" Content="A button" />
<my:MyUserControl Owner="{Binding ElementName=Button1}" x:Name="myUserControl1" />

(请注意,您的示例不起作用,因为grid1继承自类型FrameworkElement,而不是Control。您需要将Owner属性更改为类型FrameworkElement才能将其设置为grid1。)

有关依赖属性的更多信息,请参阅这个优秀的教程: http: //www.wpftutorial.net/dependencyproperties.html

于 2012-05-17T05:48:47.073 回答
0

你应该使用 DependancyProperty 进行绑定,如之前所述,你也可以使用RelativeSource

Parent={Binding RelativeSource={RelativeSource AncestorType=Grid}}
于 2012-05-17T05:52:03.937 回答