[英]Master Detail MVVM with Prism and XAML binding view in data context
我有以下虛擬應用程序,在其中嘗試用兩個視圖構建主詳細信息。 第一個是集合視圖,我可以成功選擇其中的一個元素,它顯示在Content Presenter數據模板中,其中的TextBlock和TextBox定義如下。
我試圖將TextBlock和TextBox移到一個視圖中,但是未能成功顯示它來顯示數據。 如果刪除TB並取消注釋該視圖,它將顯示該視圖,但視圖中的TB不會填充。
當然,我的想法是我將擁有不止一種類型。
主窗口
<Window x:Class="MyApp.Views.MainWindow"
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:views="clr-namespace:MyApp.Views"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
xmlns:viewModel="clr-namespace:MyApp.ViewModels"
prism:ViewModelLocator.AutoWireViewModel="True"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="LayoutRoot">
<StackPanel Orientation="Horizontal">
<views:CollectionView DataContext="{Binding myItemCollection}">
</views:CollectionView>
<ContentPresenter x:Name="Detail" Content="{Binding myItemCollection.SelectedViewModel}">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type viewModel:TextViewModel}">
<StackPanel>
<TextBlock Text="{Binding Name}"></TextBlock>
<TextBox Text="{Binding Text}"></TextBox>
<!--<views:TextView/>-->
</StackPanel>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
</StackPanel>
</Grid>
文字檢視
<UserControl x:Class="MyApp.Views.TextView"
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"
xmlns:local="clr-namespace:MyApp.Views"
xmlns:viewModel="clr-namespace:MyApp.ViewModels"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<StackPanel>
<TextBlock Text="Text Item"/>
<TextBlock Text="{Binding Name}"></TextBlock>
<TextBox Text="{Binding Text}"></TextBox>
</StackPanel>
</Grid>
您需要從TextView
刪除prism:ViewModelLocator.AutoWireViewModel="True"
屬性。
它的作用是從容器中提取適當的視圖模型,並將視圖模型分配給TextView.DataContext
。 另一方面,在模板中,您沒有顯式地將模板數據傳遞給TextView
控件,因此應該通過DataContext
自動繼承來繼承它。 但這是行不通的,因為TextView.DataContext
是由prism:ViewModelLocator.AutoWireViewModel="True"
顯式設置的。
如果需要使用視圖模型自動連接,則始終可以從引用范圍設置該屬性,即在“使用”視圖的XAML中,例如:
<StackPanel>
<views:TextView prism:ViewModelLocator.AutoWireViewModel="True" />
</StackPanel>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.