2012-03-26 59 views
7

这应该很简单,但我无法使其工作。 我有一个窗口(主XAML应用程序窗口)将文本块绑定到窗口的属性

我定义类型的属性格式“测试”(谁和INT ID和DateTime TestDate)

 public Test CurrentTest 
    { 
     get 
     { 
      return currentTest; 
     } 
     set 
     { 
      currentTest = value; 
      OnPropertyChanged("CurrentTest"); 
     } 
    } 

我已经添加了OnPropertyChanged默认地将Impl :

public event PropertyChangedEventHandler PropertyChanged; 
    private void OnPropertyChanged(String property) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(property)); 
     } 
    } 

现在我尝试将它绑定到窗口上的文本块。 但它不工作:

<TextBlock Text="{Binding Source={StaticResource CurrentTest}, Path=TestDate, StringFormat=dd/MM/yyyy, TargetNullValue=Not Yet Set}"></TextBlock> 

,这不工作之一:

<TextBlock> 
      <TextBlock.Text> 
       <Binding ElementName="CurrentTest" Path="TestDate" TargetNullValue="not yet set" Mode="OneWay"></Binding> 
      </TextBlock.Text> 
     </TextBlock> 

我应该怎么做才能有文本块显示此属性的日期?

+2

我想你知道如何设置的DataContext正确的,但是旁边的PropertyChanged代码的执行,你有这个类的背后? :INotifyPropertyChanged – Silvermind 2012-03-26 15:58:13

+0

你还检查了输出窗口的具体绑定错误? – Silvermind 2012-03-26 16:00:49

+0

你在哪里正确的INotifyPropertyChanged – Dani 2012-03-26 16:11:43

回答

19

可以使用的RelativeSource属性:

<TextBlock Text="{Binding Path=CurrentTest.TestDate, 
          RelativeSource={RelativeSource Mode=FindAncestor, 
                 AncestorType=Window}}" /> 
+0

这一个工程,但它只有一次,我已经将INotifyPropertyChanged添加到窗口类 - 所以谢谢@SilverMind以及! – Dani 2012-03-26 16:11:21

+0

为什么StaticResource不起作用? – Dani 2012-03-26 16:13:00

+0

@Dani,你为什么认为它应该? StaticResource用于访问资源,而不是视图的属性... – 2012-03-26 16:43:55

相关问题