如何获得给定DataGrid
的{{1}}。我在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 est ,该列上的属性已更改),当我需要SingleClickEditProperty
实例时,我将获得DataGridTextColumn
。
答案 0 :(得分:2)
我认为您可以使用this
使用此代码,您可以在Visual Tree中找到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,请尝试使用this article中的绑定。
祝你好运。<强>更新强>:
我明白这是怎么回事。下一个答案不会那么容易,但它是银色的:) 那么,为什么你不能使用VisualTreeHelper从DataGridColumn找到DataGrid?因为,Visual Tree中不存在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绑定到附加属性所有者(参见第2页并将下一个代码添加到[BINDING]部分):
{Binding Source={StaticResource ownerContainer}, Path=Item}
这就是全部。在代码中,如果我们引用DataGridColumn,我们就可以拥有DataGrid:
DataGrid owner = (DataGrid)dataGridColumn.GetValue(DataGridHelper.OwnerProperty);**
希望这个原则对你有帮助。