재산

2012-11-15 4 views
0

내가 간단한 사용자 정의 사용자 컨트롤이 의존성 결합을 다음과 같이재산

<Grid x:Name="LayoutRoot"> 
    <StackPanel> 
     <TextBlock Text="{Binding DisplayText}"/> 
     <TextBlock Text="{Binding PersonName}"/> 
    </StackPanel> 
</Grid> 

내가에서 MainPage.xaml에서 사용을 :

<local:WindowsPhoneControl1 x:Name="customControl" DisplayText="test"> 

</local:WindowsPhoneControl1> 

MainPage.xaml.cs를 내가 할 경우 :

PersonName = "George"; 
customControl.DataContext = this; 

그런 조지이 표시되지만 테스트은 그렇지 않습니다. 이것은 의미가 있지만 DisplayText 속성에 바인딩하는 방법을 모르겠습니다.

물론, 다음은이 표시되지 않습니다 조지 때문에 작동하지 않습니다

customControl.DataContext = customControl; 

이는 WP/실버 라이트 개발을위한 작업을해야 있습니다, 그래서 AncestorType 같은 물건을하지 않을 수 있습니다 사용할 수 있습니다 (반드시 유용하지는 않습니다)

+0

종속성 속성 값 우선 순위에 대한이 문서를 읽어야합니다. http://msdn.microsoft.com/en-us/library/ms743230.aspx – Guillaume

답변

1

아마 여러 가지 방법이 있습니다. 하나는 다음과 같습니다. 사용자 정의 컨트롤에 종속성 속성을 PersonName으로 추가하고 일반 등록 정보를 DisplayText (사용자가 바인딩하지 않았으므로 필요 없음)으로 추가합니다.

public static readonly DependencyProperty = 
    DependencyProperty.Register("PersonName", typeof(string), typeof(MyUserControl), null); 

public string DisplayText { get; set; } 
public string PersonName 
{ 
    get { return (string)GetValue(PersonNameProperty); } 
    set { SetValue(PersonNameProperty, value); } 
} 

그런 다음, 사용자 정의 컨트롤의 DataContextLayoutRoot (생성자에서 초기화 후)로 설정합니다.

public MyUserControl() 
{ 
    InitializeComponent(); 
    LayoutRoot.DataContext = this; 
} 

편집 다음 방법

쉽게 할 수있다 (확실히 더 직접적이다), 그러나 당신은 RelativeSource를 사용하여 사용하여 특성 DisplayText에 바인딩 할 수 있습니다 실버 라이트 5. 필요합니다.

<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, 
           Path=DisplayText}"/> 

는 그래서 여기에 사용자 컨트롤의 DataContext에 여전히 MainPage로 설정 될 수 있으며,이 하나 개의 요소에 대한 데이터 소스 사용자 정의 컨트롤의 코드 숨김 클래스로 지적 될 수있다.

+0

PersonName 종속성 속성을 추가하면 PersonName = "{Binding PersonName} "맞습니까? 나는 당신의 다른 솔루션을 사용할 수 있었으면 좋겠지 만 불행히도 AncestorType을 사용할 수 없다. (설명 된대로) – uWat

+0

@uWat'AncestorType'은 Silverlight의 이후 버전에서 작동해야합니다. 그렇지 않으면'ElementName'을 대신 사용할 수 있을지 궁금합니다. 확인 중 ... – McGarnagle

+0

@uWat hm, AncestorType은 Silverlight에서 지원되지만 버전 5 만 지원됩니다. 그리고 'ElementName'이 작동하지 않는 것 같습니다. 하지만 네, 의존성 속성 접근법에는'{Binding PersonName}'이 필요합니다. – McGarnagle