如何在Listview MVVM中绑定命令

时间:2018-03-21 20:46:36

标签: c# mvvm uwp

我希望当我点击我的项目时,此项目可以执行我的命令

查看:

<Page
x:Class="p1.View.listTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:p1.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
DataContext="{Binding SecondPageInstance, Source={StaticResource Locator}}" 
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"  Margin="0,0,0,-70">
    <Button Command="{Binding ChangeView}" Content="ReturnButton" HorizontalAlignment="Left" Margin="70,554,0,0" VerticalAlignment="Top"/> 
    <ListView ItemsSource="{Binding Items}" SelectedItem="{Binding ChangeView}" HorizontalAlignment="Left" Height="278" Margin="19,38,0,0" VerticalAlignment="Top" Width="594">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Name}"/>
                    <Button Command="{Binding ChangeView}" Content="Change View"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
 </Grid>
</page>

ViewModel:

public RelayCommand ChangeView{ get; private set; }

public VM_liste(INavigationService navigationService)
{
     _navigationService = navigationService;
     ChangeView= new RelayCommand(_ChangeView);
}

private void _ChangeView()
{
     _navigationService.GoBack();
}

但我点击了我的selectedItem或按钮。空无一物。 但是,如果我点击我的ReturnButton它正在工作......

2 个答案:

答案 0 :(得分:2)

你需要像这样将DataContext设置为ListViewModel实例。

<Button Command="{Binding ChangeView1}" Content="ReturnButton"/> 
<ListView ItemsSource="{Binding Items}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}"/>
                <Button Command="{Binding ChangeView2}" Content="Change View"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

你的ViewModels:

public class ListViewModel {
    public ObservableCollection<ListItemViewModel> Items => ...;
    public RelayCommand ChangeView1 => ...;
}

public class ListItemViewModel {
    public string Name => ...;
    public RelayCommand ChangeView2 => ...;
}

答案 1 :(得分:0)

另一种方式:你可以尝试这个例子。

<DataTemplate>
          <Button
              Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl},Mode=FindAncestor},Path=DataContext.OpenItemCommand}">
          </Button>
</DataTemplate>