これが使えると思います
このコードを使用すると、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を取得する必要がある場合は、この記事のバインディングを使用してみてください。
幸運を。
更新:
私は何が問題なのか理解しています。次の答えはそれほど簡単ではありませんが、それはシルバーライトです:)では、なぜVisualTreeHelperを使用してDataGridColumnからDataGridを見つけることができないのでしょうか。なぜなら、DataGridColumnはビジュアルツリーに存在しないからです。DataGridColumnは、UIElementではなくDependencyObjectを継承します。VisualTreeを忘れると、新しいアイデアは次のようになります。追加の添付プロパティをDataGridColumnに追加します-Ownerという名前で、DataGridをこのプロパティにバインドします。ただし、DataGridColumnはDependencyObjectであり、ElementNameによるバインディングはSilverlight4では機能しません。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コンテナ-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にバインドします(p.2を参照し、[BINDING]セクションに次のコードを追加します)。
{Binding Source={StaticResource ownerContainer}, Path=Item}
それで全部です。コードでは、DataGridColumnへの参照がある場合、所有されているDataGridを取得できます。
DataGrid owner = (DataGrid)dataGridColumn.GetValue(DataGridHelper.OwnerProperty);**
この原則がお役に立てば幸いです。