草庐IT

c# - 数据绑定(bind)到 WinForm

coder 2024-06-25 原文

我有一个包含 10 个文本框的表单 (CustomerInfoForm)。每个 TextBoxes 的默认 Text 属性是在设计时定义的。子类 CustomerInfoForm.CustomerInfo 包含用于保存在表单中输入的数据的属性。包含数据的子类将序列化为 XML。

在自动生成的表单代码中,每个文本框都有一行代码将数据源绑定(bind)到文本框

this.customerInfoBindingSource = new System.Windows.Forms.BindingSource(this.components);

C# ide 为每个文本框自动生成的代码:

this.txtCustomer.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.customerInfoForm_CustomerInfoBindingSource, "CustomerName", true));
this.txtCustomer.Location = new System.Drawing.Point(60, 23);
this.txtCustomer.Name = "txtCustomer";
this.txtCustomer.Size = new System.Drawing.Size(257, 20);
this.txtCustomer.TabIndex = 0;
this.txtCustomer.Text = "CustomerName";

(我注意到在 IDE 生成的代码中 Text 属性直到 DataBinding 之后才设置)。

当我运行该项目时,表单会在 TextBoxes 中显示默认值。但是,当按下 SaveButton 以序列化 MyForm.CustomerInfo 子类中的属性时,它们都是空的。由于这些值只会从表单更改,我希望我不必实现接口(interface) INotifyPropertyChanged

我是否遗漏了一些基本的或简单的东西?

包含数据序列化的表单代码附在下面

using System;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization;

namespace SimpleCustomerInfo
{
    // You must apply a DataContractAttribute or SerializableAttribute
    // to a class to have it serialized by the DataContractSerializer.

    public partial class CustomerInfoForm : Form
    {
        CustomerInfo ci = new CustomerInfo();

        public CustomerInfoForm()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(CustomerInfo));
            FileStream writer = new FileStream(@"C:\Users\Me\temp\testme.xml", FileMode.Create);
            serializer.WriteObject(writer,ci);
            writer.Close();
        }

        [DataContract(Name = "Customer", Namespace = "net.ElectronicCanvas")]
        public class CustomerInfo
        {
            [DataMember]
            public string CustomerName { get; set; }
            [DataMember]
            public PhoneInfo PhonePrimary { get; set; }
            [DataMember]
            public PhoneInfo PhoneDays { get; set; }
            [DataMember]
            public PhoneInfo PhoneEvening { get; set; }
        }

        public class PhoneInfo
        {
            public string number { get; set; }
            public string type { get; set; }
            public bool textOk { get; set; }
        }
    }
}

编辑——对于可能发生在这个问题上的其他人

using System;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization;

namespace SimpleCustomerInfo
{


    public partial class CustomerInfoForm : Form
    {
        CustomerInfo ci;

        public CustomerInfoForm()
        {
            InitializeComponent();
            ci = new CustomerInfo();
            ci.CustomerName = "My Customer Name";
            ci.PhoneDays.number = "888-888-8888";
            customerInfoForm_CustomerInfoBindingSource.DataSource = ci;

        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            DataContractSerializer serializer = new DataContractSerializer(typeof(CustomerInfo));
            FileStream writer = new FileStream(@"C:\Users\me\temp\testme.xml", FileMode.Create);
            serializer.WriteObject(writer,ci);
            writer.Close();
        }
        // You must apply a DataContractAttribute or SerializableAttribute
        // to a class to have it serialized by the DataContractSerializer.
        [DataContract(Name = "Customer", Namespace = "net.ElectronicCanvas")]
        public class CustomerInfo
        {
            [DataMember]
            public string CustomerName { get; set; }
            [DataMember]
            public PhoneInfo PhonePrimary { get; set; }
            [DataMember]
            public PhoneInfo PhoneDays { get; set; }
            [DataMember]
            public PhoneInfo PhoneEvening { get; set; }

            // Constructor is needed to instantiate the PhoneInfo classes
            // within the CustomerInfo class
            public CustomerInfo()
            {
                PhonePrimary = new PhoneInfo();
                PhoneDays = new PhoneInfo();
                PhoneEvening = new PhoneInfo();
            }
        }

        public class PhoneInfo
        {
            public string number { get; set; }
            public string type { get; set; }
            public bool textOk { get; set; }
        }
    }
}

最佳答案

首先您需要决定是使用数据绑定(bind)还是直接操作Text 属性。这两种方法不应混合在一起。

如果你想使用数据绑定(bind)而不是代码中缺少一行:

public Form1()
{
    InitializeComponent();
    customerInfoBindingSource.DataSource = ci;  // This is the missing line
}

您需要让您的 customerInfoBindingSource 知道数据源。

如果添加此行,那么在设计时分配的 Text 将被绑定(bind)数据源中的文本覆盖。如果您想使用绑定(bind),您应该使用数据源进行操作,而不是直接设置 Text 字段。像这样:

public Form1()
{
    InitializeComponent();

    ci.CustomerName = "TestCustomerName";
    customerInfoBindingSource.DataSource = ci;
}

关于c# - 数据绑定(bind)到 WinForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6393819/

有关c# - 数据绑定(bind)到 WinForm的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  3. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  4. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  5. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  6. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  7. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  8. FOHEART H1数据手套驱动Optitrack光学动捕双手运动(Unity3D) - 2

    本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01  客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02  数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit

  9. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

  10. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

随机推荐