Reputation: 161
I've a StackPanel
that contains three different DataGrid
, this is the structure:
<StackPanel orientation="Vertical" x:Name="DataGridContainer">
<DataGrid />
<DataGrid />
<DataGrid />
</StackPanel>
each DataGrid
bind a different ItemSource
, and each DataGrid
bound the same SelectionChanged
event.
What I need to do is remove the Selection
from all the DataGrid, except on the clicked one.
Suppose that the SelectionChanged
event is this:
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
/*
1. Get the DataGrid selected by the user
2. Get all the DataGrids contained in DataGridContainer
3. Iterate over all controls and remove the selection except for the DataGrid saved on the step1
*/
}
how can I get all the DataGrid of DataGridContainer
and apply this logic?
UPDATE
What I tried:
var datagrid = (DataGrid)sender;
var datagridList = DataGridContainer.Children.OfType<DataGrid>();
foreach(var dt in datagridList)
{
if(dt != datagrid)
{
dt.UnselectAll();
}
}
doesn't seems to working, the datagridList is empty
Thanks for any help.
Upvotes: 0
Views: 38
Reputation: 169150
UnselectAll()
triggers a new SelectionChanged
event. Try this:
<StackPanel Orientation="Vertical" x:Name="DataGridContainer"
DataGrid.SelectionChanged="DataGridContainer_SelectionChanged"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding}" />
</DataGrid.Columns>
<s:String>A</s:String>
<s:String>A</s:String>
<s:String>A</s:String>
</DataGrid>
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding}" />
</DataGrid.Columns>
<s:String>B</s:String>
<s:String>B</s:String>
<s:String>B</s:String>
</DataGrid>
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding}" />
</DataGrid.Columns>
<s:String>C</s:String>
<s:String>C</s:String>
<s:String>C</s:String>
</DataGrid>
</StackPanel>
private bool _handle = true;
private void DataGridContainer_SelectionChanged(object sender, RoutedEventArgs e)
{
if (_handle)
{
var datagrid = e.OriginalSource as DataGrid;
if (datagrid != null)
{
var datagridList = DataGridContainer.Children.OfType<DataGrid>();
foreach (var dt in datagridList)
{
if (dt != datagrid)
{
_handle = false;
dt.UnselectAll();
_handle = true;
}
}
}
}
}
Upvotes: 1