axcelenator axcelenator - 1 year ago 141
C# Question

Remove an object from ObservableCollection by clicking an item in GridView C#

I have an observable collection:

private ObservableCollection<Icon> MyContactInst;

The collection holds some objects which are changed in real time by Add Button and Remove Button.

I view the objects in a GridView:

<GridView Name="GridView2" Grid.Row="2" ItemsSource="{x:Bind MyContactInst}"
<DataTemplate x:DataType="data:Icon">
<StackPanel Orientation="Vertical">
<Image Width="65" Source="{x:Bind IconImagePath}"/>
<TextBlock FontSize="16" Text="{x:Bind FullName}"/>
<TextBlock FontSize="10" Text="{x:Bind Age}"/>

I want to click on one of the objects in the GridView and then clicking the Remove Button to erase it from the collection and the GridView. Is there any efficient way to do that?


Answer Source

There are multiple things needed to achieve what you want:

1) Add a public property of type bool to class Icon. Class Icon also needs to implement the INotifyPropertyChanged interface. You can find a tutorial how to do that here:

The code you'll need to add looks like this:

private bool isSelected; 

public bool IsSelected
      return isSelected;
      isSelected = value;

2) Bind to that value via XAML:

     <Style TargetType="{x:Type GridViewRow}">                              
           <Setter Property="IsSelected" Value="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}"/>                 

What we achieved so far is that every Icon in the GridView (which repesents all Icons in your Observable Collection) will have its IsSelected Property set to true if you select it in your GridView.

3) Now removing Icons from your Observable Collection can just be done via

public void RemoveIcon()
    foreach (Icon icon in MyContactInst)
        if (icon.IsSelected == true)

You can trigger this function via events or via Command binding to a button.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download