默认情况下,当我创建一个DataGrid来选择一行时,我需要单击单元格内的控件。
我想选择该行,只要单击该行即可。
有办法吗?
<DataGrid AutoGenerateColumns="False"
CanUserAddRows="False"
IsReadOnly="True"
Style="{StaticResource DataGridStyle}"
HorizontalContentAlignment ="Center"
VerticalContentAlignment ="Center"
VerticalScrollBarVisibility="Auto"
SelectionMode="Single"
ItemsSource="{Binding Items, Mode=OneWay}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding Name}"
Width="4*" />
<DataGridTextColumn Header="Description"
Binding="{Binding Description}"
Width="4*" />
</DataGrid.Columns>
答案 0 :(得分:2)
如果即使您不想单击特定的单元格也要选择行,则应为DataGridRow添加ItemContainerStyle和EventSetter,如下所示:
private void DataGridRow_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var dataGridRow = (DataGridRow)sender;
if (dataGridRow != null)
{
var dataGridRowParent = FindParent<DataGrid>(dataGridRow);
if (dataGridRowParent != null)
{
dataGridRowParent.SelectedItem = dataGridRow.Item;
}
}
}
public static T FindParent<T>(DependencyObject child) where T : DependencyObject
{
//get parent item
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
T parent = parentObject as T;
if (parent != null)
return parent;
else
return FindParent<T>(parentObject);
}
,然后在后面的代码中,您可以从发件人那里获取datarowgrid,然后遍历可视化树以获取datagrid本身(例如,如果您不想使用x:name进行调用),然后只需设置SelectedItem作为dataGridrow.Item
{{1}}