简体   繁体   English

如何在XAML中设置从文件加载的ComboBox DataContext?

[英]How can I set ComboBox DataContext that was loaded from a file, in XAML?

I am trying to understand Binding so I have come up with a very simple program to try and test it. 我试图了解Binding,所以我想出了一个非常简单的程序来对其进行测试。

I have the following element in my MainWindow: 我的MainWindow中包含以下元素:

<ComboBox Name="comboBox1" ItemsSource="{Binding ComboItems}" />

In my Code I have the following observable collections: 在我的代码中,我具有以下可观察的集合:

private readonly ObservableCollection<string> comboItems = 
    new ObservableCollection<string>();
public ObservableCollection<string> ComboItems
{
    get {return comboItems; }
} 

I can successfully add items this way at any point during runtime as long as the combobox was in the MainWindow XAML from the very beginning: 只要组合框从一开始就在MainWindow XAML中,我就可以在运行时的任何时候以这种方式成功添加项目:

ComboItems.Clear();
ComboItems.Add("Item");

My question is, how can I get this ComboBox to update if I load it from a file? 我的问题是,如果我从文件中加载该组合框,该如何更新? I have the following code to save and load the file: 我有以下代码来保存和加载文件:

File.WriteAllText("ComboBox.xaml", saveComboBox)

This is just the last line in my save I have other items that don't seem to matter for this discussion. 这只是我保存的最后一行,我还有其他内容似乎与本次讨论无关。

ComboBox comboBox = System.Windows.Markup.Xamlreader.Load(stream) as ComboBox;

This saves and loads my combobox successfully. 这样可以成功保存并加载我的组合框。 The problem I am encountering now is that the code: 我现在遇到的问题是代码:

ComboItems.Clear();
ComboItems.Add("Item");

No longer works. 不再有效。 I am in the process of trying to learn Data Binding for a new project that I will be doing. 我正在尝试学习将要进行的新项目的数据绑定。 This project will require the loading of xaml files for the user interface and I need to fill the ComboBox after it has been loaded. 该项目将需要为用户界面加载xaml文件,并且在加载ComboBox之后需要填充它。

What is the simplest and most efficient solution to this problem? 什么是最简单,最有效的解决方案?

I don't know if the XamlReader will even preserve the bindings, read the documentation, it has limitations. 我不知道XamlReader是否会保留绑定,请阅读文档,它有局限性。 I would not recommend doing this anyway. 我不建议这样做。 If the binding is gone you could create a new one in code, partially defeats the purpose of saving it of course. 如果绑定不存在,则可以在代码中创建一个新的绑定,当然会部分破坏保存它的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM