开发者

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?


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.


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


Visibility = Hidden


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜