且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数据从 MainWindow 传递到 MainWindow 内的用户控件?

更新时间:2023-12-06 08:17:22

UserControl 永远不应该有一个私有"控件视图模型,当您将其分配给 UserControl 的 XAML 中的 DataContext 时.相反,它应该公开可以绑定到外部提供的视图模型对象的属性的依赖属性.

A UserControl should never have a "private" view model, as you assign it to the DataContext in the UserControl's XAML. It should instead expose dependency properties that could be bound to properties of an externally provided view model object.

像这样声明一个 ItemsSource 属性:

Declare an ItemsSource property like this:

public partial class UserControl1 : UserControl
{
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register(
            nameof(ItemsSource), typeof(IEnumerable), typeof(UserControl1));

    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    public UserControl1()
    {
        InitializeComponent();
    }
}

然后像这样绑定 ListView:

And bind the ListView like this:

<UserControl ...>
    ...
    <ListView ItemsSource="{Binding ItemsSource,
                            RelativeSource={RelativeSource AncestorType=UserControl}}">
        ...
    </ListView>
    ...
</UserControl>

当您使用 UserControl 时,将属性绑定到视图模型属性:

When you use the UserControl, bind the property to a view model property:

<TabItem Header="UC1">
    <local:UserControl1 ItemsSource="{Binding OrderList}"/>
</TabItem>

最后一个 XAML 片段假定 UserControl 的 DataContext 中的对象具有 OrderList 属性.当 TabControl 绑定到具有该属性的视图模型对象集合时,这将自动发生.

The last XAML snippet assumes that the object in the UserControl's DataContext has a OrderList property. This would automatically happen when the TabControl is bound to a collection of view model objects with that property.

或者,让 UserControl 的 XAML 中的元素直接绑定到继承的 DataContext 中对象的属性.

Alternatively, let the elements in the UserControl's XAML directly bind to the properties of the object in the inherited DataContext.

<UserControl ...>
    ...
    <ListView ItemsSource="{Binding OrderList}">
        ...
    </ListView>
    ...
</UserControl>

您的控件不必公开其他可绑定属性,但它只能与实际提供预期源属性的 DataContext 对象一起使用.

Your control would not have to expose additional bindable properties, but it would only work with DataContext objects that actually provide the expected source properties.