且构网

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

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

更新时间:2023-12-06 08:12:34

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

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 属性:

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.