c# - 定义 DataContext,但不要设置它

标签 c# wpf

我的 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/

相关文章:

c# - 在 DataGridView 中设置所有列运行时的默认值

c# - 如何将 DataSet a 转换为 DataReader?

c# - WPF 如何使边框宽度扩展以填充 DockPanel 中的可用空间

c# - 在网格中显示列表框

wpf - WPF 应用程序的安装程序解决方案(具有更新/试用支持)

c# - 在 dot net core 中初始化后台服务的正确方法

c# - Sharepoint 编程有多好/多坏?

c# - DataTable.Columns.Clear 和列排序后的 DataAdapter.Fill NullReferenceException

c# - 具有分层数据模板和多种类型的 WPF TreeView

c# - 为什么在工作线程上的 View 模型中分配字符串绑定(bind)属性不会抛出参数异常