如何从 C# 将视图数据上下文重新连接到 XAML?

How to re-wire View data context to XAML from C#?

我已经将我的视图的数据上下文设置为它在视图后面的代码中关联的 ViewModel。但在阅读 a question on the MVVM pattern, 后,建议将此胶水代码移动到视图的 XAML 标记。

Google 向我展示了在 XAML、by setting a namespace to the VM and setting data context.

中设置上下文的示例

尽管在我的例子中,MainViewModel 采用了 CustomerRepository 实例的 参数,我不确定如何在 XAML 中设置它,基于前面的例子。

有谁知道如何将数据上下文移动到视图的 XAML?

这就是我目前在 C# 中设置视图代码的方式:

    public partial class MainView : Window
    {
        private MainViewModel ViewModel { get; set; }

        public MainView()
        {
            InitializeComponent();
            ViewModel = new MainViewModel(CustomerRepository.Instance);
            this.DataContext = ViewModel;

        }

    }

您可以像这样在 xaml 中实例化您的视图模型:

<Window x:Class="MyWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Test" 
            xmlns:viewModel="clr-namespace:ViewModels"> 
        <Window.DataContext>
            <viewModel:ExampleViewModel/>
        </Window.DataContext>
</Window>


您解释说您的视图模型构造函数有一个存储库参数。您是否需要此构造函数进行单元测试?

通常您可以在视图模型的无参数构造函数中新建您的存储库实例。

public class MainViewModel : ObservableObject, INotifyPropertyChanged
{

    private static CustomerRepository _customerRepository;

    // existing constructor
    public MainViewModel(CustomerRepository customerRepository)
    {
        _customerRepository = customerRepository;
    }

    // new parameterless constructor
    public MainViewModel(CustomerRepository customerRepository)
    {
        if (DesignerProperties.GetIsInDesignMode(this))
        {
            _customerRepository = new CustomerRepository();         
        }
    }
}


检查是否处于设计模式

在 xaml 中创建视图模型时还需要考虑一件事:当您打开视图时,会在设计时调用视图模型构造函数。 因此,您需要将构造函数中在设计时没有任何意义的任何代码包装到 "only when not in design time" 条件中。 如果不这样做,您的视图将在设计器中打开并出现错误。

此回复中对此进行了解释:Check if in design mode