Muhammad Saifullah
Muhammad Saifullah

Reputation: 4292

AppBarButton is not binding to MVVM Relay command in ListView

Hi I am trying to add AppBarButton in a ListView and binded command to RelayCommand in ViewModel here is my xaml code

    <DataTemplate x:Key="MyTemplage" >
        <Grid HorizontalAlignment="Stretch">
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="4*" />
                <ColumnDefinition Width="1*" />
                <ColumnDefinition Width="1*" />
            </Grid.ColumnDefinitions>
    <AppBarButton Grid.Column="1" Command="{Binding DoCommand,Mode=OneWay}">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="ms-appx:///assets/doIcon.png"></BitmapIcon>
                </AppBarButton.Icon>                    
            </AppBarButton>
            </DataTemplate>
<ListView HorizontalAlignment="Left" Margin="0,45,0,0" Background="Khaki" VerticalAlignment="Top" ItemsSource="{Binding AList, Mode=TwoWay}"
        ItemTemplate="{StaticResource MyTemplage}">
    </ListView>

here is my Relay command code in VM

private RelayCommand _DoCommand;

    /// <summary>
    /// Gets.
    /// </summary>
    public RelayCommand DoCommand
    {
        get
        {
            return _DoCommand
                ?? (_DoCommand = new RelayCommand(
                                      () =>
                                      {
                                          DoSomething();
                                      }));
        }
    }

DoCommand is not raising in ViewModel. If I register click event handler in code behind it works fine. also AppBarButton is wokring fine with MVVM if I use it in Page.Bottombar.

any ideas?

Upvotes: 0

Views: 1209

Answers (1)

Igor Ralic
Igor Ralic

Reputation: 15006

The problem is that the binding inside the ListView DataTemplate is not to the ViewModel object, but to a different DataContext, in your case it's binding to a list called AList which is inside the ViewModel and contains a list of model classes - so the binding engine is essentially looking for DoCommand inside that model class.

In order to get the binding to work, you must make sure that the binding is pointing to the whole ViewModel DataContext, where the RelayCommand actually is. One way you could do that is to bind to some element in your page which has the DataContext set to the whole ViewModel:

Command="{Binding DataContext.DoCommand, ElementName=pageRoot, Mode=OneWay}"

In this case, I'm binding to pageRoot, where pageRoot is the name of the root page element of your page which has the proper DataContext set - ViewModel where the RelayCommand actually is.

Upvotes: 2

Related Questions