【问题标题】:How to avoid the overwriting in the DataBinding?如何避免 DataBinding 中的覆盖?
【发布时间】:2022-01-22 02:07:20
【问题描述】:

我是编程新手,在这里需要帮助...我想创建一个带有组合框项的绑定。 但是 DataBinding 没有添加新的 DataBind,它会覆盖旧的,因为循环。所以我想如果你在组合框中选择一个“Profilname”,就会显示“路径”。

但到目前为止,由于覆盖,只会显示最后加载的 .txt 文件。

现在我的问题是:如何避免在 (foreach) 循环中覆盖 DataBind?

有关信息:有一个文件夹包含许多 .txt 文件,这些文件都称为:“profile.txt”。程序用一个循环搜索所有文件,然后用另一个循环在文件中搜索一行,其中包含单词“profile_name”。然后名称必须显示在组合框中,路径必须绑定到组合框中的“项目”/“文本”。

如果我的代码令人困惑或写得不是很强大,我希望这是可以理解和抱歉的,我正在学习......

            foreach (string profiletxt in Directory.EnumerateFiles(profiledirectory, "profile.txt", SearchOption.AllDirectories))
            {
                foreach (string line in System.IO.File.ReadAllLines(profiletxt))
                {
                    if (line.Contains("profile_name"))
                    {
                        string remLine = line.Remove(0, 15);
                        string dLine = remLine.Replace("\"", "");
                        // dataBinding
                        var listProfiles = new List<Profile>() {
                        new Profile() {Path = profiletxt, Name = dLine,},
                        };

                        materialComboBox1.DataSource = listProfiles;
                        materialComboBox1.DisplayMember = "Name";
                        materialComboBox1.ValueMember = "Path";
                    }
                    
                }
                if (materialComboBox1.SelectedIndex == -1)
                {
                    MessageBox.Show("Error, couldn't find Profiles");
                }
            }


        public class Profile
        {
            public string Path {   get; set; }
            public string Name { get; set; }
        }

【问题讨论】:

  • 您可能希望在循环内将项目添加到listProfiles,然后在处理完所有文件后在循环外分配绑定。

标签: c# data-binding


【解决方案1】:

ComboBox 使用包含可用项目的 ItemSource。在您的内部 foreach 循环中,您为每个找到的配置文件项声明一个新的配置文件列表:

var listProfiles = new List<Profile>() {
    new Profile() {Path = profiletxt, Name = dLine,},
};

materialComboBox1.DataSource = listProfiles;

相反,您可能希望在第一个 foreach 循环之前创建一个新的配置文件列表

var listProfiles = new List<Profile>();

在内部循环中,将您的新发现添加到列表中

listProfiles.Add(new Profile() {Path = profiletxt, Name = dLine});

然后,在外循环之后,您只能分配一次新的 ItemSource。

您的代码中还有其他新设计缺陷:

  1. 应该不需要在 .xaml.cs“代码隐藏”中设置 DisplayMember 和 ValueMember。相反,它属于 xaml 代码本身,因为它们是静态的。

  2. 作为更一般的建议,请考虑不要在您的代码中执行任何类型的“业务规则”或数据保存。相反,您喜欢将 UI(“视图”)与数据(“模型”)分开,而“视图模型”将这两者分开并实现业务规则。关于这种 MVVM 编程模式有很多很好的介绍。

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2015-05-15
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2017-08-08
    • 2019-06-15
    相关资源
    最近更新 更多