2013-06-07 4 views
9

일부 DependencyProperties (여기서는 단 하나의 문자열 속성)와 함께 UserControl을 만들었습니다. UserControl을 인스턴스화 할 때 UserControl의 속성을 설정할 수 있으며 예상 한대로 표시됩니다. Binding을 사용하여 정적 텍스트를 바꿀 때 아무 것도 표시되지 않습니다. 다음과 같이UserControl DependencyProperty에 바인딩

내 UserControl을 보인다 :

<User Control x:Class="TestUserControBinding.MyUserControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="30" d:DesignWidth="100"> 
    <Grid> 
    <Label Content="{Binding MyText}"/> 
    </Grid> 
</UserControl> 

코드가 뒤에 :

namespace TestUserControBinding { 

    public partial class MyUserControl : UserControl { 
    public MyUserControl() { 
     InitializeComponent(); 
     this.DataContext = this; 
    } 

    public static readonly DependencyProperty MyTextProperty = 
        DependencyProperty.Register(
         "MyText", 
          typeof(string), 
          typeof(MyUserControl)); 

    public string MyText { 
     get { 
     return (string)GetValue(MyTextProperty); 
     } 
     set { 
     SetValue(MyTextProperty, value); 
     } 
    }// MyText 

    } 
} 

내 MainWindow를이 시도, 모든 것이 예상대로입니다 :

<Window x:Class="TestUserControBinding.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:TestUserControBinding" 
     Title="MainWindow" Height="350" Width="525"> 
    <StackPanel> 
    <local:MyUserControl MyText="Hello World!"/> 
    </StackPanel> 
</Window> 

그러나 작동하지 않음 :

<Window x:Class="TestUserControBinding.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:TestUserControBinding" 
     Title="MainWindow" Height="350" Width="525"> 
    <StackPanel> 
    <local:MyUserControl MyText="{Binding Path=Text}"/> 
    <Label Content="{Binding Path=Text}"/> 
    </StackPanel> 
</Window> 

라벨의 동작이 올바른지, 그래서 속성 "텍스트"아무 문제가

내 실수 란 없다? 나는 몇 시간 동안 상고하지만 잊어 버린 것을 찾을 수 없습니다. 당신의 UserControl에서 다음 바인딩

답변

10

다음으로 myText 속성 작업에 직접 텍스트를 설정하는 방법

<Label Content="{Binding MyText}"/> 

잘 모르겠어요. 이 작업을 수행하려면 UserControlDataContext을 설정해야합니다.

관계없이이 바인딩은 문제입니다. 사용자 시나리오를 이해하면 UserControlDataContext에 바인딩하고 싶지는 않습니다. MyText 속성을 반드시 가질 필요는 없기 때문입니다. UserControl 그 자체, 특히 DependencyProperty에 바인딩하고 싶습니다. 이를 위해 다음처럼 RelativeSource 바인딩을 사용해야합니다

<Label Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MyUserControl}}, Path=MyText}"/> 

이을 MyUserControl 다음 거기으로 myText 속성을 찾기 위해 시각적 트리를 탐색합니다. UserControl의 위치에 따라 달라지는 DataContext에 종속되지 않습니다. 이 경우

local 당신이 UserControl에 정의해야합니다 네임 스페이스를 참조합니다

<UserControl x:Class="TestUserControBinding.MyUserControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:TestUserControBinding" 
     ...> 

그리고 두 번째 예는 그 시점에서 작동합니다.

+0

@Brian ... 코드 "this.DataContext = this;" DataContext를 로컬로 설정해야합니다. 그래야하지 않니? – Nishant

+4

오, 그래, 나는 그것을 놓쳤다. 그러나 만약 당신이'UserControl'을 만들고 있다면, 저는'DataContext'를 수동으로 설정하는 것이 좋지 않다고 생각합니다. DataContext는 컨테이너에서 상속되거나 할당 된 컨텍스트를 나타 내기위한 것입니다. 'RelativeSource' 바인딩은 여러분이 원하는'DataContext' 상속 흐름을 방해하지 않으면 서 원하는 결과 ('DependencyProperty'에 대한 바인딩)를 얻을 수 있도록합니다. 'UserControl' 소비자가 자신의'DataContext'를 설정하면'DataContext'를 무시하려고 시도하면 실패합니다. 정확히 문제가있는 –

+2

입니다.MyUserControl의 DataContext를 자체로 설정하는 대신 MyUserControl의 여는 태그에서'x : Name = "MyName"'을 사용하고 Binding이 다음과 같이 변경됩니다 :'

관련 문제