Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a TextBlock to a Window's Property

Tags:

binding

wpf

This should be simple, yet I can't get it to work. I have a window (main xaml app window)

I've defined a propery of type "Test" (who has and int ID and DateTime TestDate)

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

I've added the OnPropertyChanged Impl:

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

and now I try to bind it to a text block on the window. But it doesn't work:

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

and this doesn't work either:

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

What should I do to have the textBlock show the Date of this property ?

like image 531
Dani Avatar asked Mar 26 '12 15:03

Dani


1 Answers

You can use the RelativeSource property:

<TextBlock Text="{Binding Path=CurrentTest.TestDate,
                          RelativeSource={RelativeSource Mode=FindAncestor,
                                                         AncestorType=Window}}" />
like image 107
Thomas Levesque Avatar answered Oct 03 '22 21:10

Thomas Levesque