繁体   English   中英

Winforms MVVM数据绑定

[英]Winforms MVVM Databinding

我正在尝试使用Winforms创建对MVVM的简单模仿。 我已经创建了从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...";
    }
}

在上面的示例中,我在ViewModel类内部调用相关的Form,然后查找具有给定名称的控件并设置值。

我想知道如何在将返回值返回到属性的情况下像“通用”那样执行此操作。

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

也许可以侦听Text属性的更改,并且哪个事件处理程序会提出该问题并不重要,或者我可能走错了方向? 有人面对吗?

提前致谢。

我在WinForms中完成此操作的方法是在表单本身内部添加数据绑定:

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

您可以使用多种技术来避免魔术弦。

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