在 C# 中使用字典填充 WPF DataGrid <String,MyClass>

Filling WPF DataGrid in C# with a Dictionary <String,MyClass>

我想用我字典中的数据填充数据网格。绑定列 Binding="{Binding Key} 有效,但试图绑定 MyClass 的值 (Binding="{Binding Value.myString} ) 我只得到 属性 not found on 'object'。我应该改变什么? 提前致谢。

我可以给你一个样品。

请看以下代码:

xaml:
Binding="{Binding MyclassDic[N_100].Id}"

cs:
xxx.Binding=new Binding(@"MyclassDic[N_100].Id");

MainWindow.xaml:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="197" Width="514.5"
        Loaded="Window_Loaded">
    <Grid RenderTransformOrigin="0.5,0.5" Margin="0,0,-1,3">
        <Grid.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform Angle="0.338"/>
                <TranslateTransform/>
            </TransformGroup>
        </Grid.RenderTransform>
        <DataGrid Name="DataGrid" AutoGenerateColumns="False" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Width="150" Binding="{Binding MyclassDic[N_100].Id}" />
                <DataGridTextColumn Header="Name" Width="150" Binding="{Binding MyclassDic[N_100].Name}" />
                <DataGridTextColumn Header="Age" Width="150" Binding="{Binding MyclassDic[N_100].Age}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

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

        private void Window_Loaded (object sender, RoutedEventArgs e) {
            List<Project> projects = new List<Project>();
            Project project = new Project();
            project.MyclassDic.Add("N_100", new Myclass(1, "Tim", 30));
            projects.Add(project);
            DataGrid.ItemsSource = projects;              
            }
        }
    }

Myclass.cs:

using System;
namespace WpfApp1 {
    public class Myclass
        {
        public int Id {
            get; set;
            }
        public String Name {
            get; set;
            }
        public int Age {
            get; set;
            }

        public Myclass (int Id,String Name, int Age) {
            this.Name = Name;
            this.Id = Id;
            this.Age = Age;
            }
        }
    }

Project.cs:

using System;
using System.Collections.Generic;

namespace WpfApp1 {
    public class Project {
        public Dictionary<String, Myclass> MyclassDic {
            get; set;
            }
        public Project () {
            MyclassDic = new Dictionary<String, Myclass>();
            }
        }
    }

输出: