WPF C#将xaml对象作为参数传递

时间:2012-05-17 05:24:50

标签: wpf xaml user-controls parameter-passing

我有一个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>

2 个答案:

答案 0 :(得分:3)

您需要将所有者属性实现为 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 。您需要更改所有者属性以键入 FrameworkElement ,以便能够将其设置为 grid1 。)

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

答案 1 :(得分:0)

U应该使用依赖属性进行绑定,如前所述,你也可以使用 RelativeSource

Parent={Binding RelativeSource={RelativeSource AncestorType=Grid}}