如何为给定的DataGrid获取DataGridColumn。我在DataGrid的子类中创建了一个附加属性,该属性应用于DataGridColumn (我没有对其进行子类)。它给了我应用附加属性的DataGridColumn,但是如何获得DataGrid引用本身?我两者都需要。
编辑:
我更感兴趣的是,在附加属性的事件处理程序中,如何获得实际承载附加属性的DependencyObject实例。也就是说,属性附加的DataGrid而不是DataGridColumn。
<my:MvvmDataGrid x:Name="_dataGrid" ... >
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn my:MvvmDataGrid.SingleClickEdit="true" .../>
</sdk:DataGrid.Columns>
</my:MvvmDataGrid>然后我有一个静态处理程序OnSingleClickEditPropertyChanged,它在附加属性的元数据上注册为PropertyChangedCallback。
当该属性被调用时(在列上更改了属性的id),当我需要DataGridTextColumn实例时,就会给我一个MvvmDataGrid。
发布于 2011-03-10 20:24:24
我想你可以用这
使用此代码,您可以在可视化树中找到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 :)那么,为什么您不能使用DataGrid从DataGridColumn中找到VisualTreeHelper呢?因为视觉树中不存在DataGridColumn。DataGridColumn继承的是DependencyObject,而不是UIElement。忘记VisualTree,新的idea将是这样的:我们向DataGridColumn命名的所有者添加附加属性,并将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容器-- DataGrid实例在StaticResource中的守护者:
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绑定到附加的属性所有者(参见第2页,并将下一段代码添加到绑定部分):
{Binding Source={StaticResource ownerContainer}, Path=Item}就这样。在代码中,如果我们引用了DataGridColumn,就可以获得拥有的DataGrid:
DataGrid owner = (DataGrid)dataGridColumn.GetValue(DataGridHelper.OwnerProperty);** 希望这个原则对你有帮助。
https://stackoverflow.com/questions/5264555
复制相似问题