0

假设我有这段代码(在 Winforms 中):

public class SomeClass
{
    public string Name { get; set; }
}

public partial class SomeControl : UserControl
{
    private SomeClass inClass;

    public string MyName { get; set; }

    public SomeControl(SomeClass someClass)
    {
        InitializeComponent();

        this.inClass = someClass;

        SetupBinding();
    }

    private void SetupBinding()
    {
        this.DataBindings.Clear();
        this.DataBindings.Add("MyName", this.inClass, "Name");
    }
}

如果我在用户控件之外更改 SomeClass.Name 的值,则属性 MyName 永远不会改变。我究竟做错了什么?

谢谢

4

1 回答 1

0

如果您想要双向数据绑定,SomeClass必须实现INotifyPropertyChanged或具有名为NameChanged的​​事件。你可以自己实现它,但我强烈推荐Fody.PropertyChanged项目。

PS:我写了一些扩展方法来创建更容易的绑定和重构友好的方式。在您的情况下,它看起来像这样:

this.BindTo(inClass, c => c.MyName , m => m.Name);

方法本身:

public static class BindingExtensions
{
    public static Binding BindTo<TControl, TControlProperty, TModel, TModelProperty>(this TControl control, TModel model, Expression<Func<TControl, TControlProperty>> controlProperty, Expression<Func<TModel, TModelProperty>> modelProperty, string format = null)
        where TControl : Control
    {
        var controlPropertyName = ((MemberExpression)controlProperty.Body).Member.Name;
        var modelPropertyName = ((MemberExpression)modelProperty.Body).Member.Name;

        var formattingEnabled = !string.IsNullOrWhiteSpace(format);
        var binding = control.DataBindings.Add(controlPropertyName, model, modelPropertyName, formattingEnabled, DataSourceUpdateMode.OnPropertyChanged);
        if (formattingEnabled)
        {
            binding.FormatString = format;
        }
        return binding;
    }
}
于 2013-06-21T08:16:25.760 回答