c# - UserControl 中的数据绑定(bind)在设计时不起作用?

标签 c# data-binding user-controls inotifypropertychanged

我有一个关于数据绑定(bind)和用户控制的小问题。

(使用 C# 2010) 构建了一个用户控件,它基本上是 ComboBox 的包装器,它有一个自定义属性,当更改时,它会设置 ComboBox 的值。相反,如果 ComboBox 中的所选项目发生变化,则该属性的值也会发生变化。

现在,我可以通过在 ComboBox 上捕获“选定值已更改”事件并设置属性来完成此操作,并且我可以在属性 setter 中设置 ComboBox 的选定值,但我想我也可以可以使用 DataBinding 做到这一点。

它几乎可以工作,但不完全是。

它在运行时有效,但在设计时无效,我想知道是否可以轻松解决这个问题。

例如,如果在设计时,我选择我的用户控件的实例,并从属性窗口中选择我的控件的自定义属性,并更改它,组合框不会反射(reflect)更改。

任何指向我遗漏的东西的指针都会受到欢迎。显然,我可以设置 ComboBox 的选定值,但如果 DataBinding 能帮我做这件事就好了。

谢谢

(这是我的用户控件。将一个放在窗体上并使用 IDE 更改“位置”属性)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsFormsApplication13
{
  public partial class UserControl1 : UserControl, INotifyPropertyChanged
  {
     public event PropertyChangedEventHandler PropertyChanged;

     public enum enumPosition : byte
     {
        Unknown, First, Second, Third
     }

     public UserControl1()
     {
        InitializeComponent();

        var bindingList = new BindingList<KeyValuePair<enumPosition, String>>();

        foreach (enumPosition value in Enum.GetValues(typeof(enumPosition)))
        {
           bindingList.Add(new KeyValuePair<enumPosition, String>(value, value.ToString()));
        }

        this.comboBox1.DisplayMember = "Value";
        this.comboBox1.ValueMember = "Key";
        this.comboBox1.DataSource = bindingList;

        this.comboBox1.DataBindings.Add("SelectedValue", this, "Position", false, DataSourceUpdateMode.OnPropertyChanged);
     }

     private enumPosition _position = enumPosition.Unknown;

     [DefaultValue(typeof(enumPosition), "Unknown")]
     public enumPosition Position
     {
        get { return _position; }
        set
        {
           if (value != _position)
           {
              _position = value;
              this.OnPropertyChanged(new PropertyChangedEventArgs("Position"));
           }
        }
     }

     private void OnPropertyChanged(PropertyChangedEventArgs e)
     {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, e);
     }
  }
}

最佳答案

对我也有用! 环境 - VS .Net 2008

我认为唯一的区别可能是“重建”应用程序而不仅仅是“构建”?

关于c# - UserControl 中的数据绑定(bind)在设计时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5142317/

相关文章:

c# - WPF 将 MouseDown 和 TouchDown 组合到同一事件

WPF ToggleButton 绑定(bind) IsChecked 禁用时

c# - WPF中UserControl中DesignWidth和Width的区别

c# - 帮助对哈希 (SHA1) 字符串进行数字签名

c# - 比较画笔和颜色

c# - 使用 .NET 的 NAudio 如何删除 mp3 文件末尾的静音波?

c# - WPF ListView ItemTemplate问题

c# - UWP x :bind two-way binding

C# 线程安全调用动态创建的控件

C# 动态表单(反射)-链接控件