Refracted Paladin
Refracted Paladin

Reputation: 12216

How do I have the Click event of a button manipulate another control in MVVM

I am using WPF(4.5) and Caliburn.Micro. I am trying to understand how to have an "event" in my View manipulate other controls in my View.

For instance:

My View has an Expander Control, a Button, and a GridView. The GridView is inside the Expander. When the user clicks the button it calls a method in the VM that populates the gridview with a BindableCollection<>. What I want to have happen is when that collection has more then 1 item I want to Expand the Expander Control automatically.

Ideas?

Upvotes: 1

Views: 271

Answers (2)

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

@cguedel method is completely valid but if you don't want to use Converters (why one more class) then in your view model have another property of type bool maybe called ShouldExpand, well why talk so much, let me show you:

class YourViewModel {
    public bool ShouldExpand {
        get {
            return _theCollectionYouPopulatedTheGridWith.Length() != 0;
            // or maybe use a flag, you get the idea !
        }
    }

    public void ButtonPressed() {
        // populate the grid with collection
        // NOW RAISE PROPERTY CHANGED EVENT FOR THE ShouldExpand property
    }
}

Now in your View use this binding instead:

<Expander IsExpanded="{Binding Path=ShouldExpand}" />

As i said before the other solution is well but i like to reduce the number of classes in my solutions. This is just another way of doing it.

Upvotes: 2

cguedel
cguedel

Reputation: 1112

You can bind to the number of items in a collection:

<Expander IsExpanded="{Binding Path=YourCollection.Length, Converter={StaticResource ResourceName=MyConverter}" />

and then in the window or usercontrol:

<UserControl... xmlns:converters="clr-namespace:My.Namespace.With.Converters">
    <UserControl.Resources>
        <converters:ItemCountToBooleanConverter x:Key="MyConverter" />
    </UserControl.Resources>
</UserControl>

and the converter:

namespace My.Namespace.With.Converters {
    public class ItemCountToBooleanConverter : IValueConverter 
    {

        // implementation of IValueConverter here
        ...
    }
}

I wrote this out of my head, so apologies if it contains errors ;)

Also: Make sure your viewModel implements the INotifyPropertyChanged interface, but I assume you already know that.

Upvotes: 2

Related Questions