[英]MVVM - listview itemsSource binding different than binding of listview's elements
我有一個問題多於問題。 我在XAML中有listView:
<ListView Margin="25,10,25,10" Name="BookListView" ItemsSource="{Binding Books}" DockPanel.Dock="Top">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}"/>
<StackPanel>
<TextBlock Text="Number: " />
<TextBlock Text="{Binding Number}" />
</StackPanel>
<Button Content="Read" Visibility="Hidden" Name="ReadButton" Command="{Binding ReadCommand}"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource Mode=TemplatedParent}}" Value="True">
<Setter TargetName="ReadButton" Property="Visibility" Value="Visible"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
為了正式起見,我的DataContext:
public MainWindow()
{
InitializeComponent();
DataContext = new BookListViewModel();
}
我的listView itemsSource綁定到我的viewModel中名為“ Book”的類的元素的observableCollection上,並且一切正常(在此代碼段中,我刪除了指定此窗口外觀的所有代碼)。
我的問題是,當單擊元素時,列表中的每個元素都包含一個按鈕。 如果我像在此代碼中那樣綁定命令,應用程序將期望ReadCommand位於Book類代碼中,就像我一直認為的那樣,它違反了MVVM模式。 所以我的問題是-該解決方案在MVVM模式中可以接受嗎? 如果不是,那我該如何從綁定到listView的observableList返回綁定到我的按鈕中的viewModel呢?
在Book
類中具有ReadCommand
屬性不會以任何方式違反MVVM。 但是,在視圖模型中使用ReadCommand
可能更合理,更方便。 在這種情況下,您可以使用RelativeSource
到達ListView的DataContext,它實際上是視圖模型:
<Button Content="Read" Visibility="Hidden" Name="ReadButton"
Command="{Binding Path=DataContext.ReadCommand, RelativeSource={RelativeSource AncestorType=ListView}}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.