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



我有一个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 中的网格作为该参数传递?

<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>

您需要将 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

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

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

最新更新