Giora Guttsait Giora Guttsait - 2 months ago 27
C# Question

Bind wpf combobox to a dictionary of <string, CustomClass>, and use data of custom class

I'd like to apologize in advance, I'm not a WPF developer, and I don't know all the terminology.

I have a WPF application, and in it, I have a combobox.

In the

MainWindow.xaml.cs
file (which I assume is the
View
part of the
MVVM
?), I have a property of type

public Dictionary<string, TeamData> Teams { get; }


And I want to bind the combobox to this dictionary.

This is what I've tried so far:

<ComboBox x:Name="TeamsDropdown" HorizontalAlignment="Left"
Margin="158,142,0,24" ItemsSource="{Binding Teams}" FontSize="18.667" Width="195"/>`


Problem is, even this binding fails
(there are no items in the dropdown)
. I know that to get the text in the combobox items to be the
key
of the selected dictionary item, I have to use
SelctedValue
or
SelectedValuePath
...

But I'm not sure which, and I can't really test it until I get it to work.

The constructor of
MainWindow
:

public MainWindow()
{

InitializeComponent();
Teams = TeamsData.Teams;

var appData = Application.UserAppDataRegistry;
object nameRegistry = null;
object ipRegistry = null;
object teamRegistry = null;

if (appData != null)
{
nameRegistry = appData.GetValue(NameRegistry);
ipRegistry = appData.GetValue(IpRegistry);
teamRegistry = appData.GetValue(TeamRegistry);
}

PlayerName = nameRegistry?.ToString() ?? "Player Name";
IpAddress = ipRegistry?.ToString() ?? "localhost";
PlayerTeam = teamRegistry?.ToString() ?? Teams.Keys.First();

NameBox.Text = PlayerName;
AddressBox.Text = IpAddress;
TeamsDropdown.SelectedItem = Teams[PlayerTeam];
}

Answer

You need set your data context to the window.

DataContext = this;

This action will refresh all bindings. Make sure you data is correctly loaded before (after Teams = TeamsData.Teams; in your example).

Other solution is use observable partern with ObservableCollection and INotifyProperty to update the combobox when the data is modified.

Comments