area9 area9 - 2 years ago 176 Question

VB .Net WPF Binding 2 controls to dictionary

I have been trying to get my head round binding in WPF forms and am lost in this. I'm trying to do binding in VB .net code. I have the interface:

Implements INotifyPropertyChanged

and if I have a dictionary:

Public Property myDict As New Dictionary(Of String, String)

which I fill up with a key-value bunch of data, then I would like to populate a combobox on a WPF window with the key. So far using the following:

myCombo.ItemsSource = myDict
myCombo.DisplayMemberPath = "Key"

Then I'm trying to link the combobox to a textblock, so that the combobox shows the key and the textblock shows the value. There are lots of these combobox-textbox combinations, so can't really hard code this or have it in xaml. The last thing I tried which does something is the following:

Dim aBinding As New Binding("Value")
aBinding.Source = myDict
myTextBlock.SetBinding(TextBlock.TextProperty, aBinding)

This then shows the textblock to have the first value in the dictionary, but doesn't alter with the combobox. I've tried binding the combobox in the same manner and with a new binding variable, which has the effect of blanking the combobox, but cannot seem to get this working.

Apologies if this is a really, really simple problem, but I'm very new at using binding in WPF, mainly because I've avoided it.

Answer Source

You may create the TextBlock binding like this:

Dim aBinding As New Binding("SelectedItem.Value")
aBinding.Source = myCombo
myTextBlock.SetBinding(TextBlock.TextProperty, aBinding)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download