Wpf 将文本块绑定到窗口';s属性

Wpf 将文本块绑定到窗口';s属性,wpf,binding,Wpf,Binding,这应该很简单,但我无法让它工作。 我有一个窗口(xaml应用程序主窗口) 我已经定义了一个类型为“Test”的属性(谁拥有和int ID以及DateTime TestDate) 我添加了OnPropertyChanged Impl: public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(String property) { if (Prope

这应该很简单,但我无法让它工作。 我有一个窗口(xaml应用程序主窗口)

我已经定义了一个类型为“Test”的属性(谁拥有和int ID以及DateTime TestDate)

我添加了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>


我应该如何让textBlock显示此属性的日期?

您可以使用RelativeSource属性:

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


我认为您知道如何正确设置DataContext,但是除了propertychanged代码的实现之外,您的类背后是否有此功能INotifyPropertyChangedAlso您是否检查了outputwindow中的特定绑定错误?您知道INotifyPropertyChanged的正确位置这一项有效,但它只在我将INotifyPropertyChanged添加到Window类后才起作用-因此也感谢@SilverMind@丹尼,你为什么认为应该?StaticResource用于访问资源,而不是视图的属性…此答案在不必实现INotifyPropertyChanged的情况下工作
<TextBlock Text="{Binding Path=CurrentTest.TestDate,
                          RelativeSource={RelativeSource Mode=FindAncestor,
                                                         AncestorType=Window}}" />