setting a Window DataContext to a property object of App

Pablo gil 86 Reputation points
2021-09-28T21:39:33.463+00:00

I want to set in xaml, the DataContext of a window to a property object of App,
but I do not know how to configure the binding, I do not know the RelativeSource
of App to set in MainWindow.xaml

DataContext="{Binding RelativeSource=???? , Path=myAppProperty }"

and then use it, for example like this:

        <TextBlock Text="{Binding Path=myField}"/>

maybe, I should use another property of the binding instead of RelativeSource

could someone help?

Developer technologies Windows Presentation Foundation
Developer technologies XAML
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-09-29T00:36:57.68+00:00

    Try two approaches:

    <TextBlock Text="{Binding myAppProperty}" DataContext="{x:Static Application.Current}" . . .  />
    
    <TextBlock Text="{Binding myAppProperty, Source={x:Static Application.Current}}"  . . . />
    

    This assumes that App contains the corresponding property. A simple one is:

    public string myAppProperty { get; set; } = "SomeText";
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.