当我使用xaml代码时。
<DataGrid Name="DataGrid1"
ItemsSource="{Binding Path=MainSearchBinding}"
HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeRows="False" CanUserSortColumns="True"
AutoGenerateColumns="False" IsTextSearchEnabled="True" IsReadOnly="True"
RowHeaderWidth="17" SelectionChanged="DataGrid1_SelectionChanged"
MouseDoubleClick="OnDoubleClick" MouseLeftButtonUp="OnMouseClick">
工作正常
切换到<WpfToolkit:Datagrid></WpfToolkit:Datagrid>
:
<WpfToolkit:DataGrid Name="DataGrid1"
ItemsSource="{Binding Path=MainSearchBinding}"
HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeRows="False" CanUserSortColumns="True"
AutoGenerateColumns="False" IsTextSearchEnabled="True" IsReadOnly="True"
RowHeaderWidth="17" SelectionChanged="DataGrid1_SelectionChanged"
MouseDoubleClick="OnDoubleClick" MouseLeftButtonUp="OnMouseClick">
我遇到了错误:
“值不能为空。参数名称:元素”
此行中有FindParent<T>(...)
:
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
public static T FindParent<T>(this 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
var parent = parentObject as T;
if (parent != null)
{
return parent;
}
else
{
return FindParent<T>(parentObject);
}
}
我的代码在这里。如果单击datagrid单元格,它将打开新选项卡。
var tabControl = (sender as DataGrid).FindParent<TabControl>();
tabControl.Items.Add(new TabItem() { Header = "Документ", Content = docview, IsSelected = true });
我知道我遗失了什么,请告诉我搬家的地方?提前谢谢。
答案 0 :(得分:2)
问题出在这一行:
var tabControl = (sender as DataGrid).FindParent<TabControl>();
WPF Toolkit DataGrid具有类Microsoft.Windows.Controls.DataGrid
,而内置WPF DataGrid具有类System.Windows.Controls.DataGrid
。如果您的sender
对象是WPF Toolkit DataGrid,并且上面代码行中的DataGrid
是内置的WPF DataGrid,那么sender as DataGrid
将为null。 WPF工具包DataGrid
与内置DataGrid
完全分开,尤其不会从中继承。
幸运的是,这个问题很容易解决。您无需将sender
转换为DataGrid
类。您的FindParent<T>
扩展程序适用于DependencyObject
,两个DataGrid
类都继承自DependencyObject
,因此您可以编写
var tabControl = (sender as DependencyObject).FindParent<TabControl>();
代替。
答案 1 :(得分:1)
从它的外观来看,你的错误将来自这条线:
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
因为child
将是null
。您正尝试将sender
投射到DataGrid
,这就是为什么它第一次有效,因为您使用的是DataGrid
。但第二次,我假设您正在使用不同的DataGrid
(也许是自定义的){所以演员阵容将返回null
。因此,在致电FindParent(...)
时,child
将为null
。
获取错误时,请查看堆栈跟踪并查看错误源自何处。它应该显示确切的行,当使用调试器查看时,您应该能够看到哪个值是null
。