将TextBlock绑定到窗口属性

10

这应该很简单,但是我无法让它工作。

我有一个窗口(主xaml应用程序窗口)

我定义了一个类型为“Test”的属性(它有一个int ID和DateTime TestDate)

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

我已经添加了OnPropertyChanged实现:

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显示这个属性的日期?


2
我想你知道如何正确设置DataContext,但是除了实现PropertyChanged代码的属性外,你的类后面是否有这个呢?: INotifyPropertyChanged - Silvermind
你是否也检查了输出窗口以查找特定的绑定错误? - Silvermind
你关于INotifyPropertyChanged的想法是正确的。 - Dani
1个回答

38
您可以使用RelativeSource属性:
<TextBlock Text="{Binding Path=CurrentTest.TestDate,
                          RelativeSource={RelativeSource Mode=FindAncestor,
                                                         AncestorType=Window}}" />

这个是有效的,但只有在我将INotifyPropertyChanged添加到Window类之后才有效-所以还要感谢@SilverMind! - Dani
@Dani,你为什么认为它应该这样呢?StaticResource 用于访问资源,而不是您视图的属性... - Thomas Levesque
这个答案可以正常工作,而无需实现INotifyPropertyChanged。 - KornMuffin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接