gpt4 book ai didi

wpf - DataTemplate 具有非空构造函数的 ViewModel ?

转载 作者:行者123 更新时间:2023-12-04 21:51:25 24 4
gpt4 key购买 nike

如何使用带有非空构造函数的 ViewModel 对 UserControl 进行数据模板化?

public PersonViewModel(Person person)
{
_person= person;
// do some stuff
}

由于 Ctor 不为空,因此在 Xaml 中绑定(bind) this 会崩溃。但是当我使用与 ViewModels 的父/子关系时,我必须将 person 对象传递给 ViewModel 的构造函数......

你如何应对这种情况?

最佳答案

 var person = new Person();
var viewModel = new PersonViewModel(person);

var view = new EditPersonView(viewModel); // use overloaded constructor to inject DataContext
// OR
var view = new EditPersonView{ DataContext = viewModel };

如果你真想 实例化 XAML 中的 View 模型,那么您需要公开一个 public Person Person属性并坚持使用无参数构造函数。只需在 Person 中执行设置你在构造函数中所做的事情。当然,现在您已经打开了一 jar 蠕虫,因为您还需要实例化 Person在带有无参数构造函数的 XAML 中,很快事情变得非常难看……

关于wpf - DataTemplate 具有非空构造函数的 ViewModel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3688421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com