显示基于数据绑定视图模型类型的控件?

问题描述:

我正在学习WPF。我发现xaml使用起来相当困难。我已经MainWindow.xaml定义是这样的:显示基于数据绑定视图模型类型的控件?

<Window x:Class="Compliance.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <ResourceDictionary Source="MainWindow.Resources.xaml"></ResourceDictionary> 
    </Window.Resources> 
    <Grid> 
    </Grid> 
</Window> 

而且MainWindow.Resources.xaml这样的:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:vm="clr-namespace:Compliance.ViewModel" 
    xmlns:vw="clr-namespace:Compliance.View"> 

    <DataTemplate DataType="{x:Type vm:Entities.AbstractEntityViewModel}"> 
     <vw:AbstractEntityView></vw:AbstractEntityView>  
    </DataTemplate>   
</ResourceDictionary> 

AbstractEntityView是这样的:

<UserControl x:Class="Compliance.View.AbstractEntityView" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 
    <StackPanel> 
     <Label Content="ID:"></Label> 
     <TextBlock Text="{Binding Path=EntityId}"></TextBlock> 
    </StackPanel> 
</UserControl> 

然后在App.xaml.cs我重写OnStartup这样的:

MainWindow window = new MainWindow(); 

    //Model class 
Individual ind = new Individual(1,"Name"); 

    //subclass of AbstractEntityViewModel 
var vm = new Entities.IndividualEntityViewModel(ind); 

window.DataContext = vm; 
window.Show(); 

但是,窗口中没有显示任何内容。

我使用了this question的答案让我的控件呈现。但是,这需要您从代码中引用视图中的元素,而我不想这样做。

是否有可能得到一个窗口来选择视图渲染基于ViewModel集作为其datacontext?或者我对MVVM应该如何工作有错误的想法?

你有正确的想法,但你没有真正告诉WPF来显示您随时随地ViewModel

我通常在ContentControl对象举办ViewModel如果我绑定到一个单一的视图模型

<Window x:Class="Compliance.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <ResourceDictionary Source="MainWindow.Resources.xaml"></ResourceDictionary> 
    </Window.Resources> 
    <Grid> 
     <ContentControl Content="{Binding }" /> 
    </Grid> 
</Window> 

通常不需要的ModelsViewModels列表的ContentControl,由于对象是作为每个项目的ContentPresenterContent属性自动插入。例如,ListBox结合ViewModels

<ListBox ItemsSource="{Binding MyCollectionOfViewModel}" /> 
+0

整齐,由于集合时不需要ContentControl。我在我的窗口定义中出现了'DataContext =“{Binding RelativeSource = {RelativeSource Self}}”'这个问题,但我得到了一个奇怪的问题(我确信我没有把它放在那里......)一旦我删除了那个工作。 – Oliver 2012-04-11 15:25:58

+0

@Oliver在绑定中引用'Self'会将绑定源设置为UI对象,而不是它的'DataContext' – Rachel 2012-04-11 16:30:05