Thursday, January 15, 2015

how to make button click work in listview on universal app ( xaml & WinRT)

If you are following MVVM pattern or using a datatemplate and trying to have a button inside a ListViewItem but the button click not working (not triggering the command), this might help.

The button gets binded to the item on the collection and if you want to manipulate the collection bound to listview, the command in most cases you might have it at the ViewModel bound to the listview. so make the button command bind to the listview data binding as below..







                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">

                                <Button Content="x" HorizontalAlignment="Left" VerticalAlignment="Center" Command="{Binding ElementName=ItemListView, Path=DataContext.RemoveButtonCommand}" CommandParameter="{Binding}"></Button>

                                <TextBlock Text="{Binding Title}"></TextBlock>





In above code, I'm setting the binding to the listview element by name and set the binding path to the elements datacontext and the command exposed through a property on the viewmodel bound to the listview.

The viewmodel would be something like this.
public myViewModel()

     this.RemoveButtonCommand = new RelayCommand(this.RemoveButtonCommandExecute);

public ICommand RemoveButtonCommand { get; set; }

please let me know in commands if this is useful or if you think more details/explanation would be helpful.