0
我正在學習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應該如何工作有錯誤的想法?
整齊,由於集合時不需要
ContentControl
。我在我的窗口定義中出現了'DataContext =「{Binding RelativeSource = {RelativeSource Self}}」'這個問題,但我得到了一個奇怪的問題(我確信我沒有把它放在那裏......)一旦我刪除了那個工作。 – Oliver 2012-04-11 15:25:58@Oliver在綁定中引用'Self'會將綁定源設置爲UI對象,而不是它的'DataContext' – Rachel 2012-04-11 16:30:05