C# 如何将DataGrid引入转换器
我有一个转换器,它需要:当前的DataGridCell,一个DataGridCellInfo对象,我正在尝试把DataGrid对象也放进去C# 如何将DataGrid引入转换器,c#,wpf,wpfdatagrid,datagridcell,imultivalueconverter,C#,Wpf,Wpfdatagrid,Datagridcell,Imultivalueconverter,我有一个转换器,它需要:当前的DataGridCell,一个DataGridCellInfo对象,我正在尝试把DataGrid对象也放进去 <Style TargetType="{x:Type DataGridCell}" x:Key="cellStyle" > <Setter Property="helpers:SearchBehaviours.IsTextMatchFocused"> <Setter.Value&g
<Style TargetType="{x:Type DataGridCell}" x:Key="cellStyle" >
<Setter Property="helpers:SearchBehaviours.IsTextMatchFocused">
<Setter.Value>
<MultiBinding Converter="{StaticResource SelectedSearchValueConverter}" FallbackValue="False">
<Binding RelativeSource="{x:Static RelativeSource.Self}"/>
<Binding Source="{x:Static helpers:MyClass.Instance}" Path="CurrentCellMatch" />
<Binding ElementName="GenericDataGrid"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
我可以想象,您可以使用
相对资源绑定
来实现您的需求。试试这个:
<Style TargetType="{x:Type DataGridCell}" x:Key="cellStyle" >
<Setter Property="helpers:SearchBehaviours.IsTextMatchFocused">
<Setter.Value>
<MultiBinding Converter="{StaticResource SelectedSearchValueConverter}" FallbackValue="False">
<Binding RelativeSource="{x:Static RelativeSource.Self}"/>
<Binding Source="{x:Static helpers:MyClass.Instance}" Path="CurrentCellMatch" />
<!-- ----> --> <Binding RelativeSource="{RelativeSource AncestorType={x:Type DataGrid}}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
-->
虽然我确实喜欢通过相对资源将其提供给转换器的给定解决方案,但也可以采用不同的方式。可以不传递DataGrid参数,而是在转换器内部通过DataGridCell上的Parent
属性从DataGridCell中查找它
为此,您需要一个父查找帮助器方法:
private T FindParent<T>(DependencyObject child)
where T : DependencyObject
{
T parent = VisualTreeHelper.GetParent(child) as T;
if (parent != null)
return parent;
else
return FindParent<T>(parent);
}
private T FindParent(DependencyObject子对象)
其中T:DependencyObject
{
T parent=visualtreeheloper.GetParent(child)作为T;
如果(父项!=null)
返回父母;
其他的
返回FindParent(父级);
}
您可以选择将此代码放在可重用的位置,甚至将其作为扩展方法,但以下是您在转换器中调用它的方式:
DataGrid parentDataGrid = FindParent<DataGrid>(dataGridCell);
DataGrid parentDataGrid=FindParent(dataGridCell);
您需要将DataGrid传递给转换器,还是可以使用DataGridCell通过父(或其他)属性获取包含的DataGrid?@VP。他们两个都很好。如果你知道一个或另一个方法,请张贴。只是在下面添加了一个答案,让它看一看。谢谢,但我仍然在下面的评论错误这一个。我认为原因是虚拟化DataGrid.System.Windows.Data中的断开连接(回收)项警告:4:找不到用于绑定的源,引用为“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.DataGrid',AncestorLevel='1'。BindingExpression:Path=;DataItem=null;目标元素是“DataGridCell”(名称=“”);目标属性为“IsTextMatchFocused”(类型为“Boolean”),很抱歉,此操作在每个单元格上都失败,原因如下:PresentationCore.dll SelectedSearchValueConverter中发生了类型为“System.ArgumentNullException”的首次意外异常错误:值不能为null。参数名称:元素
DataGrid parentDataGrid = FindParent<DataGrid>(dataGridCell);