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

后端 未结 2 1973
一个人的身影
一个人的身影 2020-12-09 18:15

I am trying to bind a dictionary\'s key to a row of the grid in a listbox, and bind the dictionary\'s value to another row of the grid. key\'s type is Book, a class thati wr

2条回答
  •  有刺的猬
    2020-12-09 18:47

    Below code will show the following:

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

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

    XAML:

    
    
        
            
                
                    
                        
                            
                                
                                
                            
                        
                    
                
            
        
    
    

    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();
                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 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; }
        }
    }
    

提交回复
热议问题