【问题标题】:Bind POCO to UserControl将 POCO 绑定到 UserControl
【发布时间】:2009-02-08 15:00:35
【问题描述】:

您好,我正在编写我的第一个 .net gui。我想知道是否需要将某些特定方式应用于我的 poco 对象,以便它们可以绑定到用户控件。我有一些对象,但我似乎无法将它们绑定到我的用户控件。

我在某处读到他们需要实现 IBindable,但我无法摆脱这样一种感觉,即有人已经消除了我必须输入到所有类中的所有重复代码。有没有办法轻松绑定这些,或者我必须使用数据集或类似的东西才能轻松地让这个绑定工作。我非常讨厌数据集,请提供一些其他不错的选择 ;-)

我正在尝试从 devexpress 工具包绑定到用户控件。

【问题讨论】:

  • 您使用的是什么工具包? WinForms, WPF, GTK, ... ?
  • 我正在使用 winforms 和 devexpress。

标签: .net data-binding poco


【解决方案1】:

哪种架构?

对于单向绑定,除了公共属性之外,您不需要任何其他东西 - 可能还有一些用于任何定制数据类型的 TypeConverter 实现(structs 等)

对于完整的 2 路绑定,您需要一个事件实现 - 任何一种:

  • 每个属性“Foo”的“公共事件 EventHandler FooChanged”
  • `INotifyPropertyChanged 实现
  • 定制的组件模型(不要去那里 - 矫枉过正)

INotifyPropertyChanged 实现为例(请注意,您可能需要移动一些代码以供重用):

public class Foo : INotifyPropertyChanged
{
    private string bar;
    public string Bar
    {
        get { return bar; }
        set { UpdateField(ref bar, value, "Bar"); }
    }
    // other properties...

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null) PropertyChanged(this,
            new PropertyChangedEventArgs(propertyName));
    }
    protected bool UpdateField<T>(ref T field, T value,
        string propertyName)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
        return false;
    }
}

要绑定 sets 数据(网格等),最简单的方法是使用泛型;基本上,minumumIList - 但你会从 public T this[int index] 索引器获得额外的元数据 - List&lt;T&gt;Collection&lt;T&gt; 等都有。更多 - BindingList&lt;T&gt; 实现 IBindingList 允许基于集合的通知事件(但仅限于 INotifyPropertyChanged - 不适用于 FooChanged 模式)。

【讨论】:

  • 我的自定义对象的属性也没有显示.. Person 具有 Address 的属性,它们都是我的 poco 对象。如何绑定地址?
  • 最简单的?通过覆盖 ToString() - 但是你如何显示它?哪些控件?
  • 对于文本框,您应该可以使用“Address.Line1”等;对于gridview,您可能需要一个展平(立面)对象。如果你想在文本框中编辑 整个 地址,你需要一个 TypeConverter
【解决方案2】:

使用 WPF,您将需要 INotifyPropertyChangedDependency Properties。另请查看 INotifyCollectionChanged 以获取收藏。

【讨论】:

    【解决方案3】:

    BindingList 可用于绑定到通用对象列表。

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多