Elegant way to change control visibility in wpf
I find more questions on this topic, but I don't find an answer.
I need to change the visibility on a control click.
In a win form application, if I am correct, I can use something like:
somecontrol.Visible = !somecontrol.Visible;
But when the application is wpf
, I cannot use this way.
Is there a way to do this in a somewhat "graceful" way, then if-else
?
Thanx
source to share
WPF UIElement.Visibility has 3 states; Visible / Hidden / Collapsed.
When hidden, the control will still affect the layout of the surrounding controls; items set to Visibility Collapsed do not take up layout space.
You can switch between visible and hidden, or reset.
somecontrol.Visibility = somecontrol.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
source to share
In WPF, the property you are trying to change is called Visibility and you can use it as described below.
uiElement.Visibility = Visibility.Hidden;
// Visibility.Collapsed;
// Visibility.Visible;
States interact as already mentioned in @Glen. What do you mean by ..
Is there a way to do this in something "graceful" way and then-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
source to share
A natural option in the context of WPF is to use the MVVM pattern. So you have a control like
<Button Content="I'm a button"
Visibility={Binding BtnVis} />
And in your DataContext you will have a public property that you can set as you wish.
class DataContext
{
public Visibility BtnVis { get; set; }
}
Another common option is to use a converter, because perhaps in your ViewModel you would like to have a bool property, not UIElement.Visibility
.
source to share