Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding a button in WPF

Tags:

wpf

I want to hide a button in WPF used in a Windows form e.g., button.visible=false

Is there an equivalent for this in WPF?

like image 624
sara Avatar asked Jun 16 '10 10:06

sara


4 Answers

Try one of these:

button.Visibility = Visibility.Hidden;
button.Visibility = Visibility.Collapsed;

Hidden hides the button but the button will still take up space in the UI. Collapsed will collapse the button such that it has zero width and height.

like image 110
Jakob Christensen Avatar answered Nov 14 '22 02:11

Jakob Christensen


You should set

button.visibility = System.Windows.Visibility.Hidden;

or

button.visibility = System.Windows.Visibility.Collapsed;

or by using the WPF XAML property set the same...

like image 41
Anthares Avatar answered Nov 14 '22 03:11

Anthares


Visibility = Hidden

like image 4
František Žiačik Avatar answered Nov 14 '22 02:11

František Žiačik


If you use the MVVM design pattern, you can make use of the "CanExecute" state of the command that is bound to the button in order to achieve this.

The default behaviour for the button would be to be displayed disabled, but you can change this so it will not be visible using the example below.


ViewModel

Property for command property:

public DelegateCommand<TypeOfBoundItem> TheCommand
{
    get; private set;
}


Instanciate the command (in constructor of view model):

TheCommand = new DelegateCommand<TypeOfBoundItem>( Execute, CanExecute );


The methods to execute the command and to decide whether it can be executed:

private bool CanExecute( TypeOfBoundItem item )
{
    return true or return false;
}

private bool Execute()
{
    // some logic
}


View

In the resources of the UserControl or Window you define some visibilty converter:

<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>


For the button, you define a binding setting the "Visibility" attribute of the button to the value of the buttons "IsEnabled" state, applying the converter.

So if the "IsEnabled" state is true - because the bound "TheCommand" returns true in its "CanExecute" method - the button will be visible.

If the "CanExecute" method of the bound command returns false, the button will not be visible.

<Button Command="{Binding TheCommand}"
        CommandParameter="{Binding}"
        Visibility="{Binding RelativeSource={RelativeSource Self},
                             Path=IsEnabled,
                             UpdateSourceTrigger=PropertyChanged,
                             Converter={StaticResource BooleanToVisibilityConverter}}">
</Button>
like image 2
Martin Avatar answered Nov 14 '22 02:11

Martin