sara
sara

Reputation: 357

Hiding a button in 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?

Upvotes: 32

Views: 80337

Answers (4)

Martin
Martin

Reputation: 5623

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>

Upvotes: 3

Jakob Christensen
Jakob Christensen

Reputation: 14956

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.

Upvotes: 68

Anthares
Anthares

Reputation: 1059

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

Upvotes: 13

František Žiačik
František Žiačik

Reputation: 7614

Visibility = Hidden

Upvotes: 5

Related Questions