简体   繁体   中英

WPF - Controlling Visibility - Better to use Binding?

For my application, I'm updating a lot of my controls to better incorporate the MVVM pattern because when I originally started the project I had never used WPF before.

My question is if it is possible to go too crazy with data binding, or should I use it almost exclusively?

For example, say I have two grids named Grid_Sample1 and Grid_Sample2. These grids are viewable based on a user clicking a button. So I have an event for that button, where I either collapse them or make them visible. Inside the event, I could write the following to hide them:

Grid_Sample1.Visibility = Visibility.Collapsed;
Grid_Sample2.Visibility = Visibility.Collapsed;

Or I could go through the trouble of binding their visibility properties:

private Visibility _grid_Sample1Visibility 
public Visibility Grid_Sample1Visibility
{
    get
    {
        return _grid_Sample1Visibility ;
    }
    set
    {
        _grid_Sample1Visibility = value;
        OnPropertyChanged("Grid_Sample1Visibility");
     }
}

And then toggling the visibility through the binding.

What is the preferred approach for seasoned WPF users? Is there any reason to use binding for something this simple?

What is the preferred approach for seasoned WPF users?

The latter, ie implementing your application logic in a view model class that is separated from the visual representation defined in the view.

Is there any reason to use binding for something this simple?

The main motivation for the MVVM pattern is that it provides separation of concerns between different components in your application which makes it easier to maintain and evolve over time. Small applications generally tend to grow bigger at some point and it won't hurt you to follow the MVVM guidelines from the very start. MVVM also greatly increases the application's testability and this is true even for the smallest application.

So may advice would be to learn and implement the MVVM pattern. It is the recommended pattern to use when developing XAML based UI applications and there is a reason for this.

Ideally, a view should just contain markup and any view-related logic that doesn't belong in the view model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM