0

我正在尝试将 Winforms 应用程序转换为 WPF 应用程序并具有以下代码:

ObservableCollection<Dictionary<string, string>> PlatypusDict =
    new ObservableCollection<Dictionary<string, string>>();
. . .
PlatypusDict = PlatypusData.getPlatypusAccountsForCentury(Convert.ToInt32(labelPlatypusName.Tag));

...这给了我这个错误消息:

无法将类型“System.Collections.Generic.Dictionary”隐式转换为“System.Collections.ObjectModel.ObservableCollection>”

...这没有任何帮助:

PlatypusDict = (System.Collections.ObjectModel.ObservableCollection<System.Collections.Generic.Dictionary<string, string>>)PlatypusData.getPlatypusAccountsForCentury(Convert.ToInt32(labelPlatypusName.Tag));

我真的不需要使用 ObservableCollection 将我的 ListView 绑定到,或者这里的解决方法/正确的方法是什么?

4

1 回答 1

2

您可以将 Dictionary 绑定到 ListView。

例子:

XAML 文件:

<Window x:Class="BindingDictionaryLB.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListView ItemsSource="{Binding}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Margin="2" Text="{Binding Key}" />
                        <TextBlock Margin="2" Text="{Binding Value}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>    
    </Grid>
</Window>

代码隐藏文件:

using System.Collections.Generic;
using System.Windows;

namespace BindingDictionaryLB
{    
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Dictionary<string, string> _source = new Dictionary<string, string>();
            for (int i = 0; i < 5; i++)
            {
                _source.Add("key_" + i, "value_" + i);
            }

            this.DataContext = _source;
        }
    }
}
于 2012-07-30T21:08:41.070 回答