Franck E
Franck E

Reputation: 729

UWP - Change button.Visibility from another class

I am trying to change multiple buttons visibility from another class. This is supposed to be easy, but I just don't understand it.

The xaml part is straight forward:

<button x:Name="whatever" Visibility="{Binding whateverName}"

The view-model could be something like this?

private Visibility vis;
    public Visibility Vis
    {
        get { return vis; }
        set { vis = value; }
    }

But if that is the case, how do I pass my button name?

To go a bit further, a services file is trying to modify the visibility value.. Thanks in advance.

Upvotes: 0

Views: 828

Answers (1)

AlexDrenea
AlexDrenea

Reputation: 8039

Since you're using Bindings, you don't need the button name identifier. The connection is made in the Binding part of the XAML:

<Button x:Name="whatever" Visibility="{Binding whateverName}"/>

What is happening there is that you are saying the Visibility property of the whatever button will be bound to the whateverName property value in your view model. So your View model needs to look like this:

private Visibility vis;
public Visibility whateverName
{
    get { return vis; }
    set { vis = value; }
}

To change the visibility of your button you need to change the value of whateverName in your view model. However, if you try, you'll notice that that won't work. The reason is that in order for the change to take effect on the button, the View model must notify the view that its property has changed. This is done with the INotifyPropertyChanged interface.

So your view model will need to look something like this:

public class Viewmodel : INotifyPropertyChanged
{
    private Visibility vis;
    public Visibility whateverName
    {
        get { return vis; }
        set
        {
            vis = value;
            OnPropertyChanged("whateverName");
        }
    }

    public void OnPropertyChanged(string pName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(pName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

In the PropertyChanged event you must pass the property name that you want to notify. In my example I just used a string value that matches the property name but there are various techniques to eliminate that "magic string".

Here's one SO question that has good answers.

Upvotes: 1

Related Questions