开发者

Binding WPF combo box to specific dictionary instance

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 ObjectDataProvider here. Just set ItemsSource of your ComboBox directly in the Window's contructor, where you initialize your instance of FolderList:

public MyWindow()
{
   InitializeComponent();

   FolderWatcher = new FolderList(...);

   ProjectCombo.ItemsSource = FolderWatcher.Folders;
}

Another option would be to set the instance of FolderList as DataContext of your window and then use binding to set ItemsSource of theComboBox`:

public MyWindow()
{
    InitializeComponent();

    FolderWatcher = new FolderList(...);

    DataContext = FolderWatcher;

}

<ComboBox Name="ProjectCombo" MinWidth="100" ItemsSource="{Binding Folders}" />

I suggest you look into MVVM pattern. If you designed your application according to that pattern, you would have a View Model instance as DataContext of your view and that View Model would expose a property you could bind to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜