简体   繁体   English

MVVM-列表视图项源绑定与列表视图元素的绑定不同

[英]MVVM - listview itemsSource binding different than binding of listview's elements

I have more of a question than problem. 我有一个问题多于问题。 I have my listView in XAML: 我在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>

And for formality my DataContext: 为了正式起见,我的DataContext:

public MainWindow()
{
    InitializeComponent();
    DataContext = new BookListViewModel();
}

My listView itemsSource is binded to observableCollection of elements of my class called "Book" in my viewModel and everything works great (in this code snippet I deleted all code which specify looks of this window). 我的listView itemsSource绑定到我的viewModel中名为“ Book”的类的元素的observableCollection上,并且一切正常(在此代码段中,我删除了指定此窗口外观的所有代码)。
My problem is that each element in my list contains a button which shows up, when element is clicked. 我的问题是,当单击元素时,列表中的每个元素都包含一个按钮。 If I bind my command as I did in this code, application will expect my ReadCommand to be in Book class code, which as I always thought violate the MVVM Pattern. 如果我像在此代码中那样绑定命令,应用程序将期望ReadCommand位于Book类代码中,就像我一直认为的那样,它违反了MVVM模式。 So my question is - is this solution acceptable in MVVM pattern? 所以我的问题是-该解决方案在MVVM模式中可以接受吗? If no, then how can I go back from binding to observableList in listView to binding the viewModel in my button? 如果不是,那我该如何从绑定到listView的observableList返回绑定到我的按钮中的viewModel呢?

Having a ReadCommand property in the Book class does not violate MVVM in any way. Book类中具有ReadCommand属性不会以任何方式违反MVVM。 However, it might be more reasonable and convenient to have the ReadCommand in your view model. 但是,在视图模型中使用ReadCommand可能更合理,更方便。 In that case, you can use RelativeSource to get to the ListView's DataContext, which is in fact the view model: 在这种情况下,您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM