简体   繁体   中英

Elegant way to change control visibility in wpf

I find more questions on this theme, but I not find answer.

I need to changing visibility on control click.

In win form app, if I am right, I can use something like:

somecontrol.Visible = !somecontrol.Visible;

But when app is wpf I cannot use this way.

Is there way to do this on something "elegant" way then if-else ?

Thanx

In WPF UIElement.Visibility has 3 states; Visible/Hidden/Collapsed.

If hidden, the control will still affect the layout of surrounding controls, elements that have a Visibility value of Collapsed do not occupy any layout space.

You can switch between visible and hidden or collapsed.

somecontrol.Visibility = somecontrol.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;

In WPF the property you're trying to change is called Visibility u can use it as described below..

uiElement.Visibility = Visibility.Hidden;
                    // Visibility.Collapsed;
                    // Visibility.Visible;

The states interact like @Glen already mentioned. What do you mean by..

Is there way to do this on something "elegant" way then if-else?

If you don't want to write the whole construct just use the shorter form..

uiElement.Visibility = uiElement.Visibility == Visibility.Visible // condition
    ? Visibility.Collapsed // if-case
    : Visibility.Visible;  // else-case

Natural option in the context of WPF is to use an MVVM pattern. So you have a control like

<Button Content="I'm a button"
        Visibility={Binding BtnVis} />

And in your DataContext you would have a public property which you can set at your wish.

class DataContext
{
    public Visibility BtnVis { get; set; }
}

Another usual option is to make use of a converter because, maybe, in your ViewModel you would like to have a bool property, not an UIElement.Visibility one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM