0

I would like to get comfortable again with C# so I decided to start with an "easy" one. I would like create a dictionary from a XML file and bind it to a combobox. These are my snippets:

XML

<configuration>
    <Paths>
        <add key="Path_DQM_CE_Prod" value="DQM-CE\DQM_CE_12.2.0_17615\QMConfigurationEditor.exe" />
        <add key="Path_DQM_CE_Test" value="DQM-CE\QMConfigurationEditor.exe" />
    </Paths>
</configuration>

Code-behind (works, I an iterate through the dictionary)

public MainWindow()
{
    InitializeComponent();
    this.DataContext = this;
    ///read XML and store into dictionary
    var xdoc = XDocument.Load(@"\\ServerXYZ\Settings_CAX_Startcenter\config.xml");

    var Paths = xdoc.Root.Descendants("Paths").Elements()
                       .ToDictionary(a => (string)a.Attribute("key"),
                                     a => (string)a.Attribute("value"));
}

XAML

<Grid>
    <StackPanel HorizontalAlignment="Left">
        <ComboBox ItemsSource="{Binding Paths}" DisplayMemberPath="Value.Key" />
    </StackPanel>
</Grid>

Pretty sure my binding is wrong but Im unable to solve it

Moritz
  • 377
  • 1
  • 6
  • 21
  • 1
    var Paths - is a local variable. Binding works with Property. See https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/data-binding-how-to-topics?view=netframeworkdesktop-4.8 – Maxim Feb 15 '23 at 14:51
  • 1
    https://stackoverflow.com/questions/20210210/binding-combobox-items-to-dictionary-of-enums?rq=1 – Maxim Feb 15 '23 at 14:53
  • @Maxim thank you for your links, especially the first one will help me to get more comfortable with C# – Moritz Feb 15 '23 at 15:19

1 Answers1

1

Paths must be a public property for you to be able to bind to it:

public MainWindow()
{
    InitializeComponent();
    this.DataContext = this;
    ///read XML and store into dictionary
    var xdoc = XDocument.Load(@"\\ServerXYZ\Settings_CAX_Startcenter\config.xml");

    Paths = xdoc.Root.Descendants("Paths").Elements()
                       .ToDictionary(a => (string)a.Attribute("key"),
                                     a => (string)a.Attribute("value"));
}

public Dictionary<string, string> Paths { get; }

You would then set the DisplayMemberPath to the name of the property of the KeyValuePair<TKey, TValue> that you want to display in the ComboBox, i.e. "Key" or "Value":

<ComboBox ItemsSource="{Binding Paths}" DisplayMemberPath="Value" />
mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    thank you! exactly what I was looking for. Need to get back to the roots, almost forgot everything -.- – Moritz Feb 15 '23 at 15:18