简体   繁体   中英

Winforms MVVM Databinding

I am trying to create simple imitation of MVVM using Winforms. I have alreadt created binding from ViewModel to Form as below:

public class FirstViewModel : ViewModel
{
    private string _name;

    [Bind(nameof(TextBox.Text), "ExampleTextBox", typeof(ExampleConverter))]
    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            RaisePropertyChanged();
        }
    }

    public FirstViewModel()
    {
        Test();
    }

    private async void Test()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));

        Name = "Binding working...";
    }
}

In above example inside ViewModel class I am calling related Form then find control with given name and set the value.

I am wondering how could I do this as 'generic' as there with return value back to property.

The solution could be to listen TextChanged event for given "ExampleTextBox" but this is not best solution since I would have to know that Text property is realted with OnTextChanged event in this control.

Maybe it is possible to listen for Text property changed and does not matter which one eventhandler will raise that, or maybe I'm going to wrong direction? Did somone faced with that?

Thanks in advance.

The way I've done it in WinForms is by adding the data bindings inside the form itself:

textBox1.DataBindings.Add("Text", _viewModel, "PropertyName");

There are several techniques you can use in order to avoid magic strings.

I would also implement the interface INotifyPropertyChanged in the model:

public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

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