【问题标题】:WPF: Data Binding with an ObservableCollection passed as parameter in a UserControl constructorWPF:在 UserControl 构造函数中作为参数传递的 ObservableCollection 的数据绑定
【发布时间】:2014-01-03 21:48:20
【问题描述】:

我有一个带有 ComboBox 的 UserControl,并且我将 ObservableCollection 绑定到它,如下所示。现在该集合填充在 UserControl 中。但是,我想在 MainWindow 中创建 ObservableCollection,并为我的 UserControl 创建另一个构造函数。这是我现在得到的,它正在工作:

public ObservableCollection<ComboBoxInfo> Items { get; private set; }

public CustomComboBox()
{
    InitializeComponent();
    Items = new ObservableCollection<ComboBoxInfo>();
    cmb.ItemsSource = Items;

    if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
    {
        this.createNameComboBox(); // ObservatoryCollection populating       
    }           
}

我尝试实现第二个构造函数并在主窗口中移动集合填充函数,但我收到一条错误消息,提示我在 UserControl 中的组合框未设置为对象的实例。理想情况下,我想要这样的东西:

public CustomComboBox(ObservableCollection<ComboBoxInfo> Items)
{
    this.Items = Items
    // Not sure if the binding should be done here or in default constructor
}

知道如何正确执行此操作吗?谢谢

【问题讨论】:

    标签: wpf binding constructor user-controls


    【解决方案1】:

    您的解决方案应包含一个ViewModel,它将设置为您的用户控件的DataContext

    这个 ViewModel 应该包含 ObservableCollection 并将其作为公共属性公开,理想情况下,它应该使用一些注入的服务提供者从一些数据存储中获取数据并使用该数据填充 ObservableCollection,最后,来自用户控件的 ComboBox 应该绑定到 ViewModel 中的那个 ObservableCollection。

    您的用户控件代码隐藏除了一些事件处理程序之外不应有任何代码来操作 UI 以在必要时响应 UI 事件...

    这就是使用 MVVM 模式在 WPF 中正确完成工作的方式。

    这是一个example,说明如何将服务注入 VM 构造函数并使用一些数据填充集合:

    public class MainWindowViewModel
    {
        private ICustomerService _customerService;
    
        public MainWindowViewModel(ICustomerService customerService)
        {
            _customerService = customerService;
            Customers = new ListCollectionView(customerService.Customers);
        }
    
        public ICollectionView Customers { get; private set; }
    }
    

    【讨论】:

    • 我试图避免使用 MVVM 模式,但我会阅读更多内容以完全理解它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 2015-08-02
    • 2016-07-19
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多