I am trying to understand Binding so I have come up with a very simple program to try and test it.
I have the following element in my 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:
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.
What is the simplest and most efficient solution to this problem?
I don’t know if the
XamlReaderwill even preserve the bindings, read the documentation, it has limitations. 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.