【问题标题】:C# how to binding the array to the button arrayC#如何将数组绑定到按钮数组
【发布时间】:2018-10-20 04:10:04
【问题描述】:

我正在练习 viewModel 的结构和数据绑定。我创建按钮并将它们添加到一个数组中,以便我可以使用 for 循环轻松管理它们。但是,我在绑定它们时似乎犯了一些错误。

这是我的代码:

public class MyForm : Form
{
    private ViewModel viewModel;
    private Button[] buttons;

    public MyForm (ViewModel viewModel)
    {
        this.viewModel = viewModel;
        InitializeComponent();

        buttons = new Button[]
        {
            button1, button2, button3, ...
        };

        for (int i = 0; i < buttons.Length; ++i)
        {
            buttons[i].DataBindings.Add("Text", viewModel, "ButtonText[" + i + "]");
        }
    }

    (...)
}

在我的 ViewModel 中

public class ViewModel
{
    private string[] buttonText;

    public string[] ButtonText
    {
        get
        {
            return buttonText;
        }
    }

    public ViewModel ()
    {
        buttonText = new string[]
        {
            "string1", "string2", "string3", ...
        };
    }

    (...)
}

当我运行它时,我得到一个ArgumentException

System.ArgumentException: '无法绑定到数据源上的属性或列“ButtonText[0]”。参数名称:dataMember'

我应该如何修改我的绑定以获得正确的程序行为? 提前致谢!

【问题讨论】:

    标签: c# winforms button data-binding windows-forms-designer


    【解决方案1】:

    您不能绑定到属性的索引项。
    如果您考虑基于反射的数据绑定,那么您将看到 viewmodel 没有名称为“ButtonText[2]”的公共属性。 DataMember 名称只是一个字符串,数据绑定将无法从那里检索索引。

    相反,您可以为每个按钮拥有自己的属性,以便对按钮的文本进行数据绑定。 并且仍然将它放在一个集合中,以供您在循环中执行的其他逻辑。

    如果您有动态按钮,您可以将按钮名称和操作集合绑定到 DataGridView,只有一个按钮列。

    【讨论】:

      猜你喜欢
      • 2014-06-06
      • 2010-11-27
      • 2016-01-31
      • 1970-01-01
      • 2021-03-18
      • 2011-09-16
      • 1970-01-01
      • 2014-06-05
      • 2023-03-30
      相关资源
      最近更新 更多