用户控件中的绑定

时间:2013-06-20 21:46:55

标签: c# .net winforms binding user-controls

让我说我有这个代码(在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永远不会更改。我做错了什么?

谢谢

1 个答案:

答案 0 :(得分: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;
    }
}