简体   繁体   English

Winforms MVVM数据绑定

[英]Winforms MVVM Databinding

I am trying to create simple imitation of MVVM using Winforms. 我正在尝试使用Winforms创建对MVVM的简单模仿。 I have alreadt created binding from ViewModel to Form as below: 我已经创建了从ViewModel到Form的绑定,如下所示:

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. 在上面的示例中,我在ViewModel类内部调用相关的Form,然后查找具有给定名称的控件并设置值。

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. 解决方案可能是侦听给定“ ExampleTextBox”的TextChanged事件,但这不是最佳解决方案,因为我必须知道Text属性是通过此控件中的OnTextChanged事件实现的。

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? 也许可以侦听Text属性的更改,并且哪个事件处理程序会提出该问题并不重要,或者我可能走错了方向? 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: 我在WinForms中完成此操作的方法是在表单本身内部添加数据绑定:

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: 我还将在模型中实现INotifyPropertyChanged接口:

public event PropertyChangedEventHandler PropertyChanged;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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