如何将文本框数据绑定到C#Windows窗体中的字典项 [英] How to Data Binding TextBox to a Dictionary Item in C# Windows Form

查看:143
本文介绍了如何将文本框数据绑定到C#Windows窗体中的字典项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文本框的数据绑定到 Dictionary< string,string> 条目。我正在尝试通过数据绑定来实现这一点,因此在用户编辑了文本框之后,内容就会更新。

I want to bind a textBox's data to a Dictionary<string,string> entry. I am trying to achieve this through data binding, so the content get updated after the user edited the textBox.

这是我所做的演示代码:

This is a demo code of what I have done:

具有名称 List 词典的classA:

A classA that has a Name and List dictionary:

class ClassA
{
    public string Name { get; set; }
    public Dictionary<string, string> List { get; set; }

    public ClassA()
    {
        this.Name = "Hello";

        this.List = new Dictionary<string, string>
        {
            {"Item 1", "Content 1"},
            {"Item 2", "Content 2"}
        };
    }
}

在表单中,绑定 textBox1 Name textBox2 List [ Item 1]

In the Form, I bind textBox1 to Name and textBox2 to List["Item 1"]:

ClassA temp = new ClassA();

public Form1()
{
    InitializeComponent();

    textBox1.DataBindings.Add("Text", temp, "Name");
    textBox2.DataBindings.Add("Text", temp.List["Item 1"], "");

    label1.DataBindings.Add("Text", temp, "Name");
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
    label1.Text = temp.List["Item 1"];
}

如果我更改 textBox1 文本, label1 内容(名称)将成功更新。

If I change textBox1 text, label1 content (Name) will successfully updated.

但是,如果我更改 textBox2 文本,则 label1 内容将显示原始的 List [ 项目1] 值。

But if I change textBox2 text, label1 content will show the original List["Item 1"] value.

如何将 textBox2 绑定到 List [ Item 1] 正确吗?

推荐答案

使用显式绑定并使用其事件以实现您的目标

Use explicit binding and consume its events to achieve your goal

        Binding binding = new Binding("Text", temp, "List");
        binding.Parse += new ConvertEventHandler(binding_Parse);
        binding.Format += new ConvertEventHandler(binding_Format);
        textBox2.DataBindings.Add(binding); 

当数据绑定控件的值更改时,将发生解析事件。

Parse event will occur when the value of a data-bound control changes.

    void binding_Parse(object sender, ConvertEventArgs e)
    {
        temp.List["Item 1"] = e.Value.ToString();
        label1.Text = temp.List["Item 1"]; 
    }

当控件的属性绑定到数据值时,将发生格式化事件

Format event will occur when the property of a control is bound to a data value.

    void binding_Format(object sender, ConvertEventArgs e)
    {
        if (e.Value is Dictionary<string, string>) 
        { 
            Dictionary<string, string> source = (Dictionary<string, string>)e.Value;
            e.Value = source["Item 1"];

        } 
    }

这篇关于如何将文本框数据绑定到C#Windows窗体中的字典项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆