Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show different controls based on a condition in WPF?

Tags:

wpf

I basically need a section of the screen to have an "authentication" box where, if you're logged in then it displays your user name and a "switch user" button, but if you're not logged in, it just displays a login button.

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

Thanks

like image 264
Max Schmeling Avatar asked Jun 25 '10 17:06

Max Schmeling


2 Answers

Since you mention binding the visibility I'll show what I did to solve a similar problem.

In your App.xaml put

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

For every control you wish to control the visibility via a boolean property in your view model you can simply do this.

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

This will toggle the visibility of the control based on IsEditable.

like image 150
Mike Avatar answered Oct 17 '22 05:10

Mike


Your option of having 2 separate controls is actually my first choice.

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

That being said, there are other options, if you want to avoid this.

For example, you could use a ContentPresenter for that "box" area, and bind it's content to a property in your DataContext that is simply defined as "object". You could then, at runtime, set it to a separate type when it's authenticated vs. non-authenticated. By specifying a DataTemplate for each of the types, WPF will automatically wire up the appropriate control for you. (This is basically a ViewModel-first MVVM style approach.)

like image 29
Reed Copsey Avatar answered Oct 17 '22 04:10

Reed Copsey