简体   繁体   English

使用wpf在列表框中绑定字典的键和值

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

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 wrote and the value's type is int. 键的类型是Book,我编写的一个类,值的类型是int。 i want to write the elements of the class and the integer value in grid. 我想在网格中写入类的元素和整数值。 Can you help me on this? 你能帮我吗? I'm quite confused on determining the itemsSource and the data type to bind. 我对确定itemsSource和要绑定的数据类型非常困惑。 thanks for helping 谢谢你的帮助

Edit: i forgot to say that i am using c# - wpf. 编辑:我忘了说我正在使用c#-wpf。 =) =)


I sent the dictionary as the itemsSource, and i specified the dictionary as type in objectdataprovider tag, and tried to send the value (int) by this code: 我将字典作为itemsSource发送,并在objectdataprovider标记中将字典指定为类型,并尝试通过以下代码发送值(int):

< TextBlock Text="{Binding Value, Mode=OneWay}" Grid.Row="1" Width="65" >

and the selecteditem was shown as [myNameSpace.Book, 4] instead of only 4. 并且selecteditem显示为[myNameSpace.Book,4],而不是4。


BookListBox.ItemsSource = LibManager.Books;

this is what I wrote in Window.xaml.cs and Books is a BookList, where BookList is a type of dictionary< Book, int> . 这是我在Window.xaml.cs中编写的,而Books是BookList,其中BookList是dictionary <Book,int>的一种类型。

and the xaml file: 和xaml文件:

< ListBox Height="571" HorizontalAlignment="Left" Margin="444,88,0,0"
          Name="BookListBox" VerticalAlignment="Top" Width="383" >
        < ListBox.Resources>
            <ObjectDataProvider x:Key="BookData"
                                ObjectType="{x:Type local:BookList}"/>
        </ListBox.Resources>
        < ListBox.ItemTemplate>
            < DataTemplate>
                < Border BorderThickness="2" BorderBrush="Black" Margin="5"
                         CornerRadius="5" Width="350" >
                    < Grid DataContext="{StaticResource BookData}" >
                        < Grid.ColumnDefinitions>
                            < ColumnDefinition/>                        
                        </Grid.ColumnDefinitions>
                        < Grid.RowDefinitions>
                            < RowDefinition/>
                            < RowDefinition/>
                        < /Grid.RowDefinitions>
                        < Label Content="count: " />
                        < TextBlock Text="{Binding Value, Mode=OneWay}"
                                    Grid.Row="1" Width="65"/>
                    < /Grid>
                < /Border>
            < /DataTemplate>
        < /ListBox.ItemTemplate>
    < /ListBox>

there is one more problem with my code-- I cant see the listed items in listbox. 我的代码还有另一个问题-我无法在列表框中看到列出的项目。 I mean I could get the values by ListBox.SelectedItem but couldn't see in the listbox. 我的意思是我可以通过ListBox.SelectedItem获取值,但在列表框中看不到。 thus I can't be sure if I could pass the integer value to where I want. 因此,我不确定是否可以将整数值传递到想要的位置。

So I think I also need help for this problem first... I write a label that I write by hand, and another label that should be filled by data binding in the same row but I can just see the first label, but I can reach the value in code behind. 因此,我认为我也首先需要针对此问题的帮助...我写了一个手写的标签,另一个标签应该由同一行中的数据绑定填充,但是我只能看到第一个标签,但是我可以达到后面代码中的值。

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. SelectedBookIndex将设置为所选书籍的索引,开始时将选择第二本书。

XAML: 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. 从Grid元素中删除DataContext="{StaticResource BookData}"

The ObjectDataProvider will create a new, empty BookList, and your TextBlock is inheriting that DataContext. ObjectDataProvider将创建一个新的空BookList,并且您的TextBlock继承了该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. 如果删除该属性,则TextBlock将从ItemsControl中的当前项目获取其DataContext,该项目将是该行的KeyValuePair。 You can probably remove the ObjectDataProvider element completely since you are creating the data in code. 由于您正在代码中创建数据,因此您可能可以完全删除ObjectDataProvider元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM