开发者

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

开发者 https://www.devze.com 2023-01-04 15:04 出处:网络
I basically need a section of the screen to have an \"authentication\" box where, if开发者_JAVA技巧 you\'re logged in then it displays your user name and a \"switch user\" button, but if you\'re not l

I basically need a section of the screen to have an "authentication" box where, if开发者_JAVA技巧 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


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.


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消