Arkadiusz
Arkadiusz

Reputation: 51

wpf button visibility in case of CommandParameter


I need to make few buttons like this:

        <fluent:Button 
        Size="Middle"
        Visibility="{Binding Path=SomeTestingMethod}" 
        Command="{Binding Path=OtherMethod}" CommandParameter="PP" 
        Some Text</fluent:Button>

visible or not in case of "CommandParameter". I tried:

public Visibility SomeTestingMethod(object o)
{
    return o.ToString == "something" ? Visibility.Visible : Visibility.Collapsed;
}

But compiler do not even check it. Also tried stuff like this:

        private Visibility _someTestingMethod;
    public Visibility SomeTestingMethod
    {
        get  {
            var commandExecutor = new RelayCommand(ButtonVisibility);

            return _statusButtonsVisibility;
            }
    }

    public void ButtonVisibility(object o)
    {
        _statusButtonsVisibility =
                     o.ToString == "something" ? Visibility.Visible : Visibility.Collapsed;
    }

"SomeTestingMethod" is then reached but "ButtonVisibility" not. I Have found other ways to reach visibility, but none of them alows me to get CommandParameter.
How to do it correctly?

Upvotes: 0

Views: 1243

Answers (2)

Eric Olsson
Eric Olsson

Reputation: 4913

I have a few comments about the code presented.

First off, do you really want to make the button disappear if the user may not click it? I ask because the ICommand interface has a CanExecute() method which can hold logic to determine if the command may be executed. When a button is bound to a property that is an instance of an object implementing the ICommand interface, the button will automatically enable/disable itself based on the results of the CanExecute() logic. Note, that if that logic does something on a different thread, you may have to force a re-query of the command availability.

If you truly want the button to disappear rather than being disabled, as mentioned by @Jason Boyd in the comments, this is best accomplished by binding the visibility to a Boolean property in the view model and using a BooleanToVisibilityConverter to show/hide the button based on true/false of the property.

The view model should implement the INotifyPropertyChanged interface to communicate property changes to update the binding target.

Hopefully, that gives you a start in the right direction.

Upvotes: 2

lord2kim
lord2kim

Reputation: 1

You can't get CommandParameter in property which you bind to Visibility property.

Get parameter in OtherMethod method and change SomeTestingMethod property. Or you can use custom BoolToVisibility converter for using parametr.

Upvotes: 0

Related Questions