2012-08-10 2 views
17

나는 가장 기본적인 예제로도 작동하도록 미쳐 가고 있습니다. 나는 내 삶이 구속력을 갖지 못하게 할 수는 없다. 여기 나를 위해 일하지 않는 슈퍼 쉬운 예입니다. 나는 틀린 일을하고 있어야한다. 사용자 지정 컨트롤 종속 속성 바인딩

내 사용자 지정 컨트롤 내 컨트롤 라이브러리 어셈블리 :

public class TestControl : Control 
{ 
    public static readonly DependencyProperty TestPropProperty = 
     DependencyProperty.Register("TestProp", typeof(string), typeof(TestControl), new UIPropertyMetadata(null)); 

    public string TestProp 
    { 
     get { return (string)GetValue(TestPropProperty); } 
     set { SetValue(TestPropProperty, value); } 
    } 

    static TestControl() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(TestControl), new FrameworkPropertyMetadata(typeof(TestControl))); 
    } 
} 

와 XAML 템플릿 : 여기

<Style TargetType="{x:Type local:TestControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:TestControl}"> 
       <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> 
        <StackPanel> 
         <TextBlock Text="Testing..." /> 
         <Label Content="{Binding TestProp}" Padding="10" /> 
        </StackPanel> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

의 내 제어 라이브러리에 대한 참조와 WPF 창에서 컨트롤을 소모 XAML :

<Grid> 
    <ItemsControl Name="mylist"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <my:TestControl TestProp="{Binding Path=Name}" /> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
</Grid> 

여기 코드는 뒤에 있습니다 :

public partial class Test2 : Window 
{ 
    public class TestObject : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
     protected void OnPropertyChanged(string PropertyName) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); 
     } 

     private int _id; 
     public int id 
     { 
      get { return _id; } 
      set { _id = value; OnPropertyChanged("id"); } 
     } 

     private string _Name; 
     public string Name 
     { 
      get { return _Name; } 
      set { _Name = value; OnPropertyChanged("Name"); } 
     } 
    } 

    public Test2() 
    { 
     InitializeComponent(); 

     mylist.ItemsSource = new TestObject[] 
     { 
      new TestObject(){ id = 1, Name = "Tedd" }, 
      new TestObject(){ id = 2, Name = "Fred" }, 
      new TestObject(){ id = 3, Name = "Jim" }, 
      new TestObject(){ id = 4, Name = "Jack" }, 
     }; 
    } 
} 

이 예제를 실행하면 4 가지 컨트롤 인스턴스가 제공되지만 각각에 대해 "테스팅 ..."TextBlock 만 표시됩니다. 내 레이블은 절대 묶여 있지 않습니다. 내가 오해하고 잘못하고있는 것은 무엇입니까?

답변

21

올바른 바인딩 소스를 설정하지 않았습니다. 당신은 RelativeSource을 설정해야 할 것 중 하나

<Label Content="{Binding TestProp, RelativeSource={RelativeSource Mode=TemplatedParent}}" /> 

또는 사용 TemplateBinding :

<Label Content="{TemplateBinding TestProp}"/> 
관련 문제