Reputation: 31
How can I add an option to remove selected row from DataGrid
?
<controls:DataGrid
x:Name="targetsDataGrid"
ItemsSource="{x:Bind Source}"
AutoGenerateColumns="False"
ColumnWidth="*"
Height="220"
Margin="0,40,0,0"
VerticalAlignment="Top"
HorizontalContentAlignment="Center"
CanUserResizeColumns="False"
CanUserSortColumns="False"
HeadersVisibility="All"
GridLinesVisibility="Horizontal">
<controls:DataGrid.Columns>
<controls:DataGridTextColumn Header="X" Binding="{Binding X}"/>
<controls:DataGridTextColumn Header="Y" Binding="{Binding Y}"/>
<controls:DataGridTextColumn Header="Z" Binding="{Binding Z}"/>
<controls:DataGridTextColumn Header="W" Binding="{Binding W}"/>
</controls:DataGrid.Columns>
</controls:DataGrid>
I prefer to do it with an external button.
Upvotes: 1
Views: 305
Reputation: 39102
I see you are using data binding, which means the items are in fact stored in a Source
collection. You can use SelectedItem
to create a two-way binding to another property which will store the selected item:
public YourItemType Selected { get; set; }
And XAML:
<controls:DataGrid
x:Name="targetsDataGrid"
ItemsSource="{x:Bind Source}"
SelectedItem="{x:Bind Selected, Mode=TwoWay}" ...
Now add a button and in its Click
event handler or Command
do:
if (Selected != null)
{
Source.Remove(Selected);
}
Make sure Source
is a ObservableCollection<YourItemType>
to make sure the DataGrid
can observe changes in the collection and update the UI accordingly.
Upvotes: 1