2010-02-23 5 views
21

많은 성공없이 클래스 인스턴스의 문자열 속성에 바인딩 할 레이블의 내용을 가져 오려고합니다.WPF : 레이블을 클래스 속성에 바인딩

XAML :

<Window x:Class="WPFBindingTest.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Window1" Height="300" Width="300">  
<Grid>   
    <Label Height="28" Margin="12,55,106,0" Name="label1" Background="Bisque" 
      Content="{Binding Source=MyFoo, Path=W1}" VerticalAlignment="Top" /> 

    <Label Height="28" Margin="12,12,106,0" Name="label2" Background="Bisque" 
      Content="{Binding Source=MyFoo, Path=W2}" VerticalAlignment="Top" /> 

    <Button Height="23" HorizontalAlignment="Right" Margin="0,0,32,48" 
      Name="button1" VerticalAlignment="Bottom" Width="89" 
      Click="button1_Click"> 
     Set Properties 
    </Button> 

</Grid> 
</Window> 

C 번호 :

namespace WPFBindingTest 
{ 
    public partial class Window1 : Window 
    { 
     public Foo MyFoo; 

     public Window1() 
     { 
      InitializeComponent();    

      MyFoo = new Foo();   
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     {  
      MyFoo.W1 = "Hello"; 
      MyFoo.W2 = "Dave"; 
     } 
    } 

    public class Foo 
    { 
     public string W1 { get; set; } 
     public string W2 { get; set; } 
    } 
} 

즉, 내가 버튼을 클릭하면, 나는이 "안녕하세요"와 "데이브"MyFoo의 속성을 설정하고 반영하는 것이 원하는 UI의 레이블. 콘텐츠를 바인딩으로 설정했지만 뭔가 잘못되었습니다. 여기서 내가 뭘 잘못하고 있니?

답변

18

당신은 당신의 Window1 인스턴스에 DataContext 당신의 MyFoo 종속성 속성을 설정할 수 있습니다

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...> 

은 자세한 내용은이 article를 참조하십시오.

MyFoo을 종속성 속성으로 만드는 것은 강제가 아닙니다. DataContext을 할당하기 전에 을 설정하면 전에 속성과 함께 작동 할 수 있습니다. (그러나 필드가있는 것은 아닙니다.) 그러나 레이블에 W1W2의 변경 값을 적용하려면 (또는 DataContect을 지정하기 전 또는 후에 값을 설정했는지 모르거나 신경 쓰지 않는 경우) Foo ~ DependencyObject이거나 인터페이스 INotifyPropertyChanged을 구현하십시오.

+1

감사합니다, 이것은 올바른 방향으로 절 지적했다. Foo가 INotifyPropertyChanged를 구현 한 다음, Window1의 DataContext를 MyFoo가 포함 된 BindingList 으로 설정합니다. 이제 레이블 내용은 다음과 같습니다. {바인딩 경로 = W1, UpdateSourceTrigger = PropertyChanged} 그리고 치료가 효과적입니다. – Gareth

+1

@Vlad'DependencyProperty'를 사용하고'INotifyPropertyChanged'를 구현하는 것의 차이점은 무엇입니까? 아니면 자신의 질문일까요? – ywm

+0

@ymw : 사실 이것은 매우 다른 질문입니다. 간단히 말해서, 둘 다 바인딩 만 가능하지만'INotifyPropertyChanged'는 좀 더 가벼우 며'DependencyProperty'는 사용하지 않으면 메모리를 사용하지 않으며 애니메이션, 스타일, 템플릿에 사용될 수 있습니다 (상위 컨테이너에서 포함 된 것으로 상속 됨). 요소) 및 훨씬 더. 예를 들어 [이 답변] (http://stackoverflow.com/a/3674530/276994)을 참조하십시오. – Vlad

6

아니면 창에 이름을 지정 : NameOfWindow 추천하고 바인딩 ElementName을을 사용

Content="{Binding ElementName=NameOfWindow, Path=MyFoo.W1}" 

전체 샘플 XAML :

<Window x:Class="WPFBindingTest.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Window1" Height="300" Width="300" Name="NameOfWindow">  
<Grid>   
    <Label Height="28" Margin="12,55,106,0" Name="label1" Background="Bisque" Content="{Binding ElementName=NameOfWindow, Path=MyFoo.W1}" VerticalAlignment="Top" /> 
    <Label Height="28" Margin="12,12,106,0" Name="label2" Background="Bisque" Content="{Binding ElementName=NameOfWindow, Path=MyFoo.W2}" VerticalAlignment="Top" /> 
    <Button Height="23" HorizontalAlignment="Right" Margin="0,0,32,48" Name="button1" VerticalAlignment="Bottom" Width="89" Click="button1_Click">Set Properties</Button> 
</Grid> 
+1

이 작동하지 않습니다. – AnjumSKhan

관련 문제