我的 Visual Studio 上有 Resharper,因此在 WPF xaml 文件中设置 DataContext 对于获取 IntelliSense 非常有用。像这样:
<UserControl ... blah blah namespace stuff >
<UserControl.DataContext>
<viewModels:FooViewModel />
</UserControl.DataContext>
<Label Text={Binding SomeText} /> <!-- I can get IntelliSense for SomeText -->
...
但是,我想在将 ViewModel/DataContext 提供给 View 之前对其进行一些初始化。像这样:
public class FooViewModel : INotifyPropertyChanged {
private Foo Model { get; set; }
public FooViewModel(Foo model) {
Model = model;
}
// Only here for WPF compatibility - I realise this might be the root of my problems :)
public FooViewModel()
: this (new Foo) {
}
public string SomeText { ... }
...
}
public class ShowFooer {
public void ShowFoo() {
Foo model = ... // get the foo from where ever
FooViewModel viewModel = new FooViewModel(model);
FooWindow window = new FooWindow(viewModel); // Push the data context into the constructor
view.Show();
...
}
}
当我通过它进行调试时,我发现创建了 2 个 FooViewModel
- 一个是我将上下文推送到构造函数中的位置,另一个是在 InitialiseComponents
中自动创建的FooWindow
的。
tl;dr: 有没有办法告诉 WPF 我已经有一个数据上下文并且我只是使用数据上下文 xaml 标记来获取 IntelliSense?有没有办法阻止它创建新的上下文?目前,我只是在编译时注释掉数据上下文行,在编码时取消注释它们。
或者另一个问题:有没有一种方法可以在构造函数之后设置数据上下文,但是可以从第二个数据上下文中初始化所有字段,而不必执行一长串 OnPropertyChanged
电话?
最佳答案
是的。你可以使用这个:
<UserControl
xmlns:viewModels="clr-namespace:..."
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance viewModels:FooViewModel,
IsDesignTimeCreatable=True}" ...> ...
有了这个,您就可以自动完成所有 vm 属性。
关于c# - 定义 DataContext,但不要设置它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41022501/