我有一个StackPanel
,其中包含三个不同的DataGrid
,这就是结构:
<StackPanel orientation="Vertical" x:Name="DataGridContainer">
<DataGrid />
<DataGrid />
<DataGrid />
</StackPanel>
每个DataGrid
绑定不同的ItemSource
,每个DataGrid
绑定相同的SelectionChanged
事件。
我需要做的是从所有DataGrid中删除Selection
,但点击的除外。
假设SelectionChanged
事件是这样的:
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
*/
}
如何获取DataGridContainer
的所有DataGrid并应用此逻辑?
更新
我尝试了什么:
var datagrid = (DataGrid)sender;
var datagridList = DataGridContainer.Children.OfType<DataGrid>();
foreach(var dt in datagridList)
{
if(dt != datagrid)
{
dt.UnselectAll();
}
}
似乎无法正常工作,datagridList为空
感谢您的帮助。
答案 0 :(得分:1)
UnselectAll()
会触发新的SelectionChanged
事件。试试这个:
<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;
}
}
}
}
}