How to show different condition based controls in WPF?

I basically need a section of the screen where there is an "authentication" field, where if you are logged in, it displays your username and the "switch user" button, but if you are not logged in, it simply displays the login button.

I could have two completely different controls, place them on the screen and bind their visibility property to IsAuthenticated, but I was hoping there were good suggestions there for a better way.

thanks

+4
source share
2 answers

Since you mention visibility binding, I will show what I did to solve a similar problem.

In your App.xaml app

<Application.Resources> <BooleanToVisibilityConverter x:Key="VisibilityOfBool" /> </Application.Resources> 

For each control that you want to control visibility using a boolean property in your view model, you can simply do this.

 Visibility="{Binding IsEditable, Converter={StaticResource VisibilityOfBool}}" 

This will switch the visibility of the IsEditable based IsEditable .

+8
source

Your choice of having two separate controls is actually my first choice.

This has the advantage of allowing you to carefully check both of your controls. You can easily use triggers to switch which control is visible based on any criteria in your DataContext. It is clean, simple and quite elegant.

There are other options if you want to avoid this.

For example, you can use the ContentPresenter for this “box” and bind it to a property in the DataContext, which is simply defined as an “object”. Then at runtime you could set it to a separate type when it is authenticated against unidentified. By specifying a DataTemplate for each type, WPF will automatically attach the appropriate control for you. (This is basically an MVPM style approach based on ViewModel-one).

+3
source

Source: https://habr.com/ru/post/1313892/


All Articles