将TextBlock绑定到Window的属性

Dan*_*ani 8 wpf binding

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

我已经定义了一个类型为"Test"的类型(谁拥有和int ID和DateTime TestDate)

      public Test CurrentTest
    {
        get
        {
            return currentTest;
        }
        set
        {
            currentTest = value;
            OnPropertyChanged("CurrentTest");
        }
    }
Run Code Online (Sandbox Code Playgroud)

我添加了OnPropertyChanged Impl:

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

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

<TextBlock Text="{Binding Source={StaticResource CurrentTest}, Path=TestDate, StringFormat=dd/MM/yyyy, TargetNullValue=Not Yet Set}"></TextBlock>
Run Code Online (Sandbox Code Playgroud)

这也不起作用:

<TextBlock>
            <TextBlock.Text>
                <Binding ElementName="CurrentTest" Path="TestDate" TargetNullValue="not yet set" Mode="OneWay"></Binding>
            </TextBlock.Text>
        </TextBlock>
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能让textBlock显示此属性的日期?

Tho*_*que 25

您可以使用RelativeSource属性:

<TextBlock Text="{Binding Path=CurrentTest.TestDate,
                          RelativeSource={RelativeSource Mode=FindAncestor,
                                                         AncestorType=Window}}" />
Run Code Online (Sandbox Code Playgroud)