4

我们正在使用 Resharper,当然我们想利用 Resharper 的 xaml 智能感知。

我们 View 的数据上下文绑定到CurrentViewmodeltype 的属性ViewModelBase。在运行时,此属性设置为使用继承自 的视图模型ViewModelBase

我已经在 View 模型中添加了这些行来设置正确的类型:

xmlns:vms="clr-namespace:PQS.ViewModel.Report"
d:DataContext="{d:DesignInstance vms:ReportFilterViewModel, IsDesignTimeCreatable=False}"

但 Resharper 仍在继续寻找ViewModelbase属性。

我还能尝试什么?

更多代码:

设置数据上下文:

<UserControl.DataContext>
    <Binding Path="ReportMainViewModel.CurrentVm"  Source="{StaticResource Locator}"/>
</UserControl.DataContext>

绑定一些东西(Products 是 ReportFilterViewmodel 上的一个属性,r# 一直在 ViewModelBase 中寻找它):

<ListBox   ItemsSource="{Binding Products.View}" Background="White" DisplayMemberPath="Name.ActualTranslation">
                    </ListBox>
4

1 回答 1

2

R# 无法静态找到将在运行时可用的具体视图模型类型,因此您需要像这样手动注释数据上下文类型:

using System.Collections.Generic;

public partial class MainWindow {
  public MainWindow() {
    Current = new ConcreteViewModel {
      Products = {
        new Product(),
        new Product()
      }
    };

    InitializeComponent();
  }

  public ViewModelBase Current { get; set; }
}

public class ViewModelBase { }
public class ConcreteViewModel : ViewModelBase {
  public ConcreteViewModel() {
    Products = new List<Product>();
  }

  public List<Product> Products { get; private set; }
}

public class Product {
  public string ProductName { get { return "Name1"; } }
}

和 XAML 部分:

<Window x:Class="MainWindow" x:Name="MainWin"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:global="clr-namespace:" mc:Ignorable="d"
        DataContext="{Binding ElementName=MainWin, Path=Current}">
  <!-- here the type of data context is ViewModelBase -->
  <Grid d:DataContext="{d:DesignInstance global:ConcreteViewModel}">
    <!-- and here is ConcreteViewModel -->
    <ListBox ItemsSource="{Binding Path=Products}">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding ProductName}"/>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
  </Grid>
</Window>

或者像这样:

<Window x:Class="MainWindow" x:Name="MainWin"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:global="clr-namespace:"
        DataContext="{Binding ElementName=MainWin, Path=Current}">
  <Grid>
    <ListBox ItemsSource="{Binding Path=(global:ConcreteViewModel.Products)}">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding ProductName}"/>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
  </Grid>
</Window>
于 2013-02-25T13:46:02.180 回答