Hercule
Hercule

Reputation: 21

How to bind Command In listview MVVM

I would like when i click on my item, this item can execute my command

View :

<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();
}

But i click, on my selectedItem Or on the button. There is Nothing. However if i click on my ReturnButton It's working...

Upvotes: 0

Views: 78

Answers (2)

narekye
narekye

Reputation: 114

Another way: You can try out this example.

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

Upvotes: 0

Markus
Markus

Reputation: 2261

You need it like this with the DataContext set to a ListViewModel Instance.

<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>

And your ViewModels:

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

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

Upvotes: 2

Related Questions