2009-07-14 5 views
165

나는 창에 들어있는 목록 (아래 참조)을 가지고있다. 창 DataContext에는 ItemsAllowItemCommand의 두 가지 속성이 있습니다.WPF Databinding : "부모"데이터 컨텍스트에 어떻게 액세스합니까?

HyperlinkCommand 속성이 창 DataContext에 대해 해결해야하는 바인딩을 얻으려면 어떻게해야합니까?

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ... 
+0

디버거에 들어가서 UI가 빌드되는 시점까지 단계별로 진행할 수 있습니까? 그렇다면 변수에 들어가서 드릴을 시도 할 수 있습니다 –

+0

간단한 솔루션 (Windows 8 Store/Metro 앱에서도 작동)은 다음과 같습니다. [http://stackoverflow.com/questions/15366609/how-to-access- 부모 - datacontext-in-window-8-store-apps/15419382 # 15419382] (http://stackoverflow.com/questions/15366609/how-to-access-parents-datacontext-in-window-8-store-apps/15419382 # 15419382) – LMK

답변

331

이 뭔가를 시도 할 수 있습니다. 이처럼 상대 소스를 사용했는데 정상적으로 작동했습니다.

이는 것

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

+2

스타일 내에서 ListBoxItem에 설정된 ContextMenu에서 내 VM의 ICommand에 바인딩하는 데이 방법을 사용했습니다. 감사합니다. –

+1

Windows 8 앱에서 어떻게합니까? "ElementName = ..."을 사용하여 작동 시키지만 DataContext는 누설됩니다. –

+3

누출로 인해 무엇을 의미합니까? – flq

6

이것은 또한 실버 라이트 5 (아마도 이전뿐만 아니라,하지만 난 그것을 테스트하지 않은)에서 작동합니다

<ListView ItemsSource="{Binding Items}"> 
    <ListView.View> 
    <GridView> 
     <GridViewColumn Header="Action"> 
     <GridViewColumn.CellTemplate> 
      <DataTemplate> 
      <StackPanel> 
       <TextBlock> 

       <!-- this binding is not working --> 
       <Hyperlink Command="{Binding AllowItemCommand}" 
          CommandParameter="{Binding .}"> 
        <TextBlock Text="Allow" /> 
       </Hyperlink> 

       </TextBlock> 
      </StackPanel> 
      </DataTemplate> 
     </GridViewColumn.CellTemplate> 
     </GridViewColumn> 
    </GridView> 
    </ListView.View> 
</ListView> 
+0

왜 좋은 생각이 아닌가요? – rolls

17

작동 : 그것은이 시점에서 사용할 수의 DataContextWindow에서, 그래서

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, 
          Path=DataContext.AllowItemCommand}" /> 

ListView도 상속합니다.
의 하위 클래스 인 유사한 컨트롤 (예 : Gridview, ListBox 등)과 마찬가지로 이후로 이러한 컨트롤에 대한 Binding은 완벽하게 작동합니다.

관련 문제