Roxy'Pro
Roxy'Pro

Reputation: 4454

Why can't I set value from my Global static class to a TextBlock XAML

Here is XAML :

<StackPanel Grid.Column="2" Orientation="Vertical" VerticalAlignment="Center" HorizontalAlignment="Left">
                <TextBlock  x:Name="lbl1"  Text="1"  Margin="0,0,0,0"  FontSize="15" Foreground="White" HorizontalAlignment="Left" FontFamily="Arial" VerticalAlignment="Bottom" />
                <TextBlock  x:Name="lbl1Text" Text="{x:Static local:Globals.CurrentUser.FullName}" Grid.Column="0" Margin="0"  FontSize="16" Foreground="White" HorizontalAlignment="Left"  FontFamily="Arial"  />
</StackPanel>

As it is possible to see I'm trying to set currently Logged in user which is being hold in STATIC class in my project.

On form load I am setting that user like Globals.CurrentUser = LoggedIn();

And when I try to set this user to my TextBlock because I WANT TO display FullName who's currently logged in I am facing this issue :

Nested types are not supported: Globals.CurrentUser.FullName

This means That I can not access property FullName from my object CurrentUser? And how could I fix this, and why is this happening?

P.S I know how to do it in code behind :

lbl1.Text = Globals.CurrentUser.FullName; //and this might work

but I think "more right" approach is to bind it to TextBlock throught XAML

Thanks guys Cheers

Upvotes: 1

Views: 536

Answers (1)

Evk
Evk

Reputation: 101523

That's because x:Static syntax is (quote from documentation):

<object property="{x:Static prefix:typeName.staticMemberName}" .../>

where

typeName: The name of the type that defines the desired static member.

staticMemberName: The name of the desired static value member (a constant, a static property, a field, or an enumeration value).

As you see - you only can use type name and ONE member name. Syntax like Global.CurrentUser.FullName is just not supported by this markup extension.

As a workaround you can use one-time binding like this:

<TextBlock Text="{Binding Source={x:Static local:Globals.CurrentUser}, Path=FullName, Mode=OneTime}" />

If you have more parts in your path, like Globals.CurrentUser.Person.FullName - you still can use binding. Since x:Static only supports one property - the rest will go in Path:

<TextBlock Text="{Binding Source={x:Static local:Globals.CurrentUser}, Path=Person.FullName, Mode=OneTime}" />

OneTime binding is not required but is a good practice and even improves perfomance a bit (though a very little of course). Bindings usually are used to create some relation between target and source (like update target when source changes and so on). In this case we don't need all that, we just need to grab a value from source (static property) and assign to target (text block text). With OneTime we are telling wpf binding to do just that and not even bother with trying to find a way to listen to source property changes (which are not possible here anyway).

Upvotes: 3

Related Questions