我正在学习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应该如何工作有错误的想法?
答案 0 :(得分:1)
你有正确的想法,但实际上并没有告诉WPF在任何地方显示ViewModel
如果我绑定到单个ViewModel,我通常会在ViewModel
对象中托管ContentControl
<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>
ContentControl
或Models
列表通常不需要ViewModels
,因为该对象会自动插入为Content
的{{1}}属性每个物品。例如,将ContentPresenter
绑定到ContentControl
ListBox
ViewModels