我想你可以用这个
使用此代码,您可以在可视树中找到 DataGridColumn 的祖先 - 您的 DataGrid。此代码实现为静态函数,但您可以将其更改为具有更多“说话”名称的扩展方法,例如 FindAncestor:
public static class UIElementExtensions
{
public static T FindAncestor<T>(this UIElement control) where T: UIElement
{
UIElement p = VisualTreeHelper.GetParent(control) as UIElement;
if (p != null)
{
if (p is T)
return p as T;
else
return p.FindAncestor<T>();
}
return null;
}
}
并使用它:
DataGrid p = dataGridColumn.FindAncestor< DataGrid >();
如果您需要从 XAML 获取 DataGrid,请尝试使用本文中的绑定。
祝你好运。
更新:
我明白这是怎么回事。下一个答案不会那么容易,但它是silverlight :) 那么,为什么你不能使用 VisualTreeHelper 从 DataGridColumn 中找到 DataGrid?因为,可视树中不存在 DataGridColumn。DataGridColumn 继承自 DependencyObject,而不是 UIElement。忘掉VisualTree吧,新思路是这样的:我们在DataGridColumn中添加附加属性,命名为Owner,并将DataGrid绑定到这个属性。但是,DataGridColumn 是 DependencyObject并且ElementName 的任何绑定在 silverlight 4 中都不起作用。我们只能绑定到 StaticResource。所以,去做吧。1) DataGridColumn 的所有者附加属性:
public class DataGridHelper
{
public static readonly DependencyProperty OwnerProperty = DependencyProperty.RegisterAttached(
"Owner",
typeof(DataGrid),
typeof(DataGridHelper),
null));
public static void SetOwner(DependencyObject obj, DataGrid tabStop)
{
obj.SetValue(OwnerProperty, tabStop);
}
public static DataGrid GetOwner(DependencyObject obj)
{
return (DataGrid)obj.GetValue(OwnerProperty);
}
}
2)DataGrid Xaml(例如):
<Controls:DataGrid x:Name="dg" ItemsSource="{Binding}">
<Controls:DataGrid.Columns>
<Controls:DataGridTextColumn h:DataGridHelper.Owner="[BINDING]"/>
</Controls:DataGrid.Columns>
</Controls:DataGrid>
3) DataGrid Container - StaticResource 中 DataGrid 实例的守护者:
public class DataGridContainer : DependencyObject
{
public static readonly DependencyProperty ItemProperty =
DependencyProperty.Register(
"Item", typeof(DataGrid),
typeof(DataGridContainer), null
);
public DataGrid Item
{
get { return (DataGrid)GetValue(ItemProperty); }
set { SetValue(ItemProperty, value); }
}
}
4)添加到您的 DataGridContainer 视图实例的资源并将 DataGrid 实例绑定到 Item 属性:
<c:DataGridContainer x:Key="ownerContainer" Item="{Binding ElementName=dg}"/>
在这里,将通过 ElementName 进行绑定。
5) 最后一步,我们将 DataGrid 绑定到附加属性 Owner(参见第 2 页并将下一个代码添加到 [BINDING] 部分):
{Binding Source={StaticResource ownerContainer}, Path=Item}
就这样。在代码中,如果我们引用 DataGridColumn,我们可以获得拥有的 DataGrid:
DataGrid owner = (DataGrid)dataGridColumn.GetValue(DataGridHelper.OwnerProperty);**
希望这个原则对你有所帮助。