2010-02-01 5 views
0

주 제어 도구 안에 서브 컨트롤이 내장되어있어 사용자가 주소를 편집 할 수 있습니다. 이 (하나의 제어에 여러 위치에 가끔) 사방에 재사용하기 때문에 나는 그렇게datacontext가 아닌 컨트롤의 속성에 어떻게 데이터 바인딩합니까?

<Controls:EditAddressUserControl DataContext="{Binding Path=HomeAddress}"/> 
<Controls:EditAddressUserControl DataContext="{Binding Path=WorkAddress}"/> 

처럼 결합하지만 선택할 수 있도록 EditAddressUserControl는 CountrySummary 개체의 메인 컨트롤의 목록에 대한 액세스를 필요로하는 주소 국가 에 속한다.

나는 EditAddressUserControl에 나라 DependencyProperty를 추가하고 지금까지 모든 음, EditAddressUserControl.Countries 속성이 올바른 국가를 가지고가는

Countries="{Binding Countries}" 

을 추가했습니다. 그러나, 어떻게 Combobox.ItemsSource에 XAML에서 데이터 바인딩을 수행합니까?

여전히 내 EditAddressUserControl의 모든 항목이 DataContext에 바인딩되기를 원하지만 ComboBoxCountries.ItemsSource는 "this.Countries"에 바인딩해야합니다.

어떻게하면됩니까?

나는이

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Controls:EditAddressUserControl}}, Path=Countries}" /> 

을 시도했습니다 I 출력 상자에 더 바인딩 오류를 본 적이 있지만, 나는 또한 콤보 상자에 항목을 보지 못했다.

+0

'EditAddressUserControl'은 하위 컨트롤입니까, 아니면 상위 컨트롤입니까? AncestorType에 부모를 지정해야합니다. – arconaut

+0

EditAddressUserControl은 포함 된 컨트롤입니다. –

답변

1

DataContext 대신 바인딩 소스에 RelativeSource을 사용하여이 작업을 수행 할 수 있습니다.

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Controls:EditAddressUserControl}}, Path=Countries}" /> 
+0

시도했지만 불행히도 작동하지 않았습니다. –

+0

제대로 설정하면 작동합니다. DP가 정의 된 조상 계층에서 적절한 클래스를 "찾기"위해 상대 소스를 가져와야합니다. 나는 당신이 배치 한 것에 기초한 구문을 추측했다. –

0

완전히 DataContext를 사용을 중지하는 것이 었습니다 할 수있는 방법 :

이 대부분 같을 것이다. 대신에 나는 = 대신의 DataContext = "..."내가 설정 주소를 설정하는 부모 컨트롤에

public static DependencyProperty AddressProperty = DependencyProperty.Register("Address", typeof(EditPostalAddressDto), typeof(EditPostalAddressControl)); 

그럼 내 컨트롤에 DependencyProperty에 추가 "..."- 컨트롤의 XAML은 다음 포함하도록 변경된다 요소 이름 바인딩의

<UserControl ..... x:Name="MainControl"> 
<TextBox Text="{Binding ElementName=MainControl,Path=Address.Region}"/> 

이제 Address 속성에 바인딩 할 수 있지만 주 데이터 컨텍스트의 속성에도 바인딩 할 수 있습니다.

관련 문제