I am new to WPF and I am trying to get databinding to work with a combo box. I have a class I created called FolderList that basically wraps around a FileSystemWatcher instance. It has a property called Folders that returns a dictionary of the folder names and their full paths.
Then for the class for my WPF window it has contains an instance of FolderList called FolderWatcher that is configured in the constructor. I would like to databind a combobox to the dictionary in that specific instance of FolderList.
I’ve found examples where there are static instances of data objects or where they are created through XAML but I can’t figure out how to bind to a specific instance.
I am not picking if this is done in XAML or C#. I’ve basically gotten this far with the ObjectDataProvider.
<Window.Resources>
<ObjectDataProvider x:Key="ProjectNames"
ObjectType="{x:Type local:FolderList}"
/>
</Window.Resources>
And here is the combo box I want to data bind. This doesn’t produce any errors but it also isn’t populated. I know enough to know I am missing something major in the ObjectDataProvider but I just don’t know what it is.
<ComboBox Name="ProjectCombo" MinWidth="100" ItemsSource="{Binding Source={StaticResource ProjectNames}, Path=Folders}" />
You don’t need a the
ObjectDataProviderhere. Just setItemsSourceof yourComboBoxdirectly in theWindow‘s contructor, where you initialize your instance ofFolderList:Another option would be to set the instance of
FolderListasDataContextof your window and then use binding to setItemsSource of theComboBox`:}
I suggest you look into MVVM pattern. If you designed your application according to that pattern, you would have a View Model instance as
DataContextof your view and that View Model would expose a property you could bind to.