【问题标题】:How is it possible to DATA bind a dictionary<string, list<string>> to a listbox in C#-WPF?如何将字典<string, list<string>> DATA 绑定到 C#-WPF 中的列表框?
【发布时间】:2018-12-27 17:24:29
【问题描述】:

C#代码-

namespace WPFDataBinding
{
    public partial class MainWindow : Window
    {
        public Person Obj { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            Obj = new Person();
            List<string> subjects1 = new List<string>();
            subjects1.Add("C"); subjects1.Add("C++"); subjects1.Add("C#");
            List<string> subjects2 = new List<string>();
            subjects2.Add("JAVA"); subjects2.Add("JS"); subjects2.Add("CSS");
            Obj.studDetail.Add("Kush", subjects1);
            Obj.studDetail.Add("Yash", subjects2);
            DataContext = this;
         }

        public class Person
        {
            private Dictionary<string, List<string>> StudDetail = new Dictionary<string, List<string>>();
            public Dictionary<string, List<string>> studDetail
            {   
                get { return StudDetail; }
                set { StudDetail = value; }
            }
        }
    }
}




WPF code------

<ListBox  FontSize="20" Height="Auto" Width="Auto" MinHeight="100" MinWidth="100" Background="Gray">
    <Label Content="{Binding Obj}">
        <Label.ContentTemplate>
            <DataTemplate>
                <ListBox Height="Auto"  FontSize="20" MinHeight="100"
    MinWidth="100" Width="Auto" Name="Sub1" 
    ItemsSource="{Binding studDetail}"/>
            </DataTemplate>
        </Label.ContentTemplate>
    </Label>
</ListBox>

我写了这段代码,但结果不是我所期望的。有人知道在这种情况下该怎么做吗?如果是,请帮忙解决。

【问题讨论】:

  • 您希望它在 ListBox 中显示什么?字典中的键,所有列表中的所有字符串组合成一个列表,还是其他?
  • @BradleyUffner 我想在列表框中显示 1 个列表,其中有一个键“Kush”。
  • @kushagrabisht:你想如何显示主题?
  • 在一个列表框中,就像一个在另一个下面的列表 @mm8
  • 没关系,我解决了。谢谢你的帮助。我很感激。

标签: c# wpf visual-studio xaml data-binding


【解决方案1】:

您可以使用IValueConverter 将数据更改为可用的形式。

如果您只想将字符串列表中的所有字符串聚集在一个列表中,则可以使用此转换器:

public class StudentDetailsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var data = value as Dictionary<string, List<string>>;
        return data.Values.SelectMany(v => v);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

您必须将其添加为 XAML 中某个可访问的资源;窗口是一种可能性。

<Window.Resources>
    <local:StudentDetailsConverter x:Key="StudentDetailsConverter" />
</Window.Resources>

然后将您的绑定更改为:

ItemsSource="{Binding Path=studDetail, Converter={staticResource StudentDetailsConverter}}"

如果您想要不同的东西,请更新您的问题。

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 2018-08-04
    • 2010-12-02
    相关资源
    最近更新 更多