WPF创建列表

时间:2012-05-25 14:38:49

标签: c# .net wpf

我在C#MAINWINDOW.xaml.cs中有一组字符串,如下所示

public class NameList : ObservableCollection<Shortcuts>
        {
            public NameList()     : base()
            {
                Add(new Shortcuts("ctrl", "b","s"));
                Add(new Shortcuts("ctrl", "b","m"));
                Add(new Shortcuts("ctrl", "b","p"));
                Add(new Shortcuts("ctrl", "b","1"));
            }
        }

        public class Shortcuts
        {
            private string firstkey;
            private string secondkey;
            private string lastkey;

            public Shortcuts(string first, string second, string last)
            {
                this.firstkey = first;
                this.secondkey = second;
                this.lastkey= last;
            }

            public string Firstkey
            {
                get { return firstkey; }
                set { firstkey = value; }
            }

            public string Secondkey
            {
                get { return secondkey; }
                set { secondkey = value; }
            }

            public string Lastkey
            {
                get { return lastkey; }
                set { lastkey = value; }
            }
        }
    }

然后在MainWindow.xaml本身我有一个组合框,我想将这些项目绑定到组合框,这就是我做的事情

<Window x:Class="Testing_learning.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:c="clr-namespace:Testing_learning"
        Title="Outlook Context Settings" Height="350" Width="525">
    <Window.Resources>
         <c:ListName Key ="NameListData"/>

    </Window.Resources>

哦BTW项目名称是 Testing_learning 这就是为什么有这个

xmlns:c="clr-namespace:Testing_learning"

但问题是当我添加这行代码时

<Window.Resources>
         <c:ListName Key ="NameListData"/>

        </Window.Resources>

我在c收到错误:ListName找不到类型ListName,为什么会这样? 有什么想法吗?

截屏1 enter image description here

截图2 enter image description here

4 个答案:

答案 0 :(得分:2)

这似乎是一个错字?您的C#具有NameList,但您的XAML具有ListName。

答案 1 :(得分:2)

您的班级定义:

public class NameList : ObservableCollection<Shortcuts>
    {
    //[…]

你的xaml:

<c:ListName Key ="NameListData"/>

NameListListName不同。由于您没有ListName类,因此您会看到“未找到ListName”错误。

答案 2 :(得分:1)

您还有一个拼写错误:Key必须是x:Key

<Window.Resources>
    <c:NameList x:Key="NameListData" />
</Window.Resources>

你已经在MainWindow类中嵌套了你的类。移出来:

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

    public class NameList : ObservableCollection<Shortcuts>
    {
        ...
    }

    public class Shortcuts
    {
        ...
    }
}

答案 3 :(得分:0)

当我将两个类移动到单独的文件时,它可以工作。

编辑:

即使类在MainWindow.xaml

中,构建也可以解决问题

enter image description here