Binding a Dictionary's key and value in a listbox with wpf Binding a Dictionary's key and value in a listbox with wpf wpf wpf

Binding a Dictionary's key and value in a listbox with wpf


Below code will show the following:

1Book 1-------2Book 2-------3Book 3

SelectedBookIndex will be set to the index of the selected book, at start the second book will be selected.

XAML:

<Window x:Class="TestDemo.MainWindow"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    Height="300" Width="300">    <StackPanel>        <ListBox             ItemsSource="{Binding Path=Books}"            SelectedValuePath="Value"            SelectedValue="{Binding Path=SelectedBookIndex}">            <ListBox.ItemTemplate>                <DataTemplate>                    <Border BorderBrush="Black" BorderThickness="2">                        <StackPanel>                            <TextBlock Text="{Binding Path=Value}" />                            <TextBlock Text="{Binding Path=Key.Name}" />                        </StackPanel>                    </Border>                </DataTemplate>            </ListBox.ItemTemplate>        </ListBox>    </StackPanel></Window>

Code behind:

using System;using System.Collections.Generic;using System.Diagnostics;using System.Windows;namespace TestDemo{    public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            Books = new Dictionary<Book, int>();            Books.Add(new Book() { Name = "Book 1"}, 1);            Books.Add(new Book() { Name = "Book 2" }, 2);            Books.Add(new Book() { Name = "Book 3" }, 3);            SelectedBookIndex = 2;            DataContext = this;        }        public Dictionary<Book, int> Books { get; set; }        private int _selectedBookIndex;        public int SelectedBookIndex        {            get { return _selectedBookIndex; }            set            {                _selectedBookIndex = value;                Debug.WriteLine("Selected Book Index=" + _selectedBookIndex);            }        }    }    public class Book    {        public string Name { get; set; }    }}


Remove DataContext="{StaticResource BookData}" from the Grid element.

The ObjectDataProvider will create a new, empty BookList, and your TextBlock is inheriting that DataContext. If you remove that attribute, the TextBlock will get its DataContext from the current item in the ItemsControl, which will be the KeyValuePair for that row. You can probably remove the ObjectDataProvider element completely since you are creating the data in code.