I want to create an observable collection and bind it to itemsource of a combobox dropdown. I need to make this collection a resource (page/grid) to be able to bind to it inside a data template. Need help in defining a class structure . A sample class structure will really help. Collection is very simple, eg a list of all countries. Important requirement is that i should be able to add items to it. Basically a collection containing countries (string) that allows me to add items.
observable collection static resource in xaml c#
For this requirement, you could make custom ObservableCollection class in the code-behind, then implement it in the xaml.
For example:
public class CountrysObservableCollection : ObservableCollection<string>
{
public CountrysObservableCollection()
{
}
}
Xaml
<Page.Resources>
<local:CountrysObservableCollection x:Key="Countrys">
<x:String>China</x:String>
<x:String>USA</x:String>
<x:String>Japan</x:String>
<x:String>England</x:String>
<x:String>Russia</x:String>
<x:String>Korea</x:String>
<x:String>Canada</x:String>
<x:String>Australia</x:String>
</local:CountrysObservableCollection>
</Page.Resources>
Usage
<ComboBox ItemsSource="{StaticResource Countrys}"/>
Update DataSource
private void Button_Click(object sender, RoutedEventArgs e)
{
var countrys = Resources["Countrys"] as ObservableCollection<string>;
countrys.Add("New World");
}
update
<Application.Resources>
<ResourceDictionary>
<local:CountrysObservableCollection x:Key="Countrys">
<x:String>China</x:String>
<x:String>USA</x:String>
<x:String>Japan</x:String>
<x:String>England</x:String>
<x:String>Russia</x:String>
<x:String>Korea</x:String>
<x:String>Canada</x:String>
<x:String>Australia</x:String>
</local:CountrysObservableCollection>
</ResourceDictionary>
</Application.Resources>
private void Button_Click(object sender, RoutedEventArgs e)
{
var countrys = Application.Current.Resources["Countrys"]as ObservableCollection<string>;
countrys.Add("New World");
}
There are a ton of examples on the web. Here is a simple one: Explain Combo Box Binding In MVVM - WPF
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.