canton7 / Stylet

A very lightweight but powerful ViewModel-First MVVM framework for WPF for .NET Framework and .NET Core, inspired by Caliburn.Micro.
MIT License
988 stars 143 forks source link

Accessing the controls on the view from the viewmodel #169

Closed chasihle closed 3 years ago

chasihle commented 3 years ago

Hi, I'd like to access controls on view from the view's view model. Primarily to enable or disable a control based on a condition. How do I go about doing that in Stylet?

thanks

canton7 commented 3 years ago

In MVVM, you'd normally put a property on your ViewModel and then bind to it from your view. For example:

<Button IsEnabled="{Binding EnableButton}">...</Button>
public class MyViewModel : Screen
{
    private bool _enableButton;
    public bool EnableButton
    {
        get => _enableButton;
        private set => SetAndNotify(ref _enableButton, value);
    }

    public EnableTheButton()
    {
        EnableButton = true;
    }
}

If you do need to access the view directly (and this is incredibly rare: you can do almost everything you could ever need using bindings, converters, attached properties and/or attached behaviors), you can do that using Screen's .View property.

chasihle commented 3 years ago

Thanks,works like a charm Charlie On Sunday, November 15, 2020, 11:31:10 AM EST, Antony Male notifications@github.com wrote:

In MVVM, you'd normally put a property on your ViewModel and then bind to it from your view. For example:

public class MyViewModel : Screen { private bool _enableButton; public bool EnableButton { get => _enableButton; private set => SetAndNotify(ref _enableButton, value); } public EnableTheButton() { EnableButton = true; } } If you do need to access the view directly (and this is incredibly rare: you can do almost everything you could ever need using bindings, converters, attached properties and/or attached behaviors), you can do that using Screen's .View property. — You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or unsubscribe.
canton7 commented 3 years ago

Great!