axcelenator axcelenator - 23 days ago 18
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}"
IsItemClickEnabled="True"
ItemClick="GridView2_ItemClick">
<GridView.ItemTemplate>
<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}"/>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>


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?

Thanks

Answer

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: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.95).aspx

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

private bool isSelected; 


public bool IsSelected
{
   get 
   {
      return isSelected;
   }
   set 
   {
      isSelected = value;
      OnPropertyChanged("IsSelected");
   }    
}

2) Bind to that value via XAML:

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

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)
        {
            MyContactInst.Remove(icon);
        }
    }
 }

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

Comments