C# 如何绑定到列表<;T>;使用DataContext?

C# 如何绑定到列表<;T>;使用DataContext?,c#,.net,wpf,xaml,C#,.net,Wpf,Xaml,我在自学C#,OOP和WPF,所以这些东西的潜力是惊人的 因此,有人能解释一下为什么在我的小测试示例中单击按钮后,Name属性出现在文本框中,而ListBox没有显示任何内容吗 XAML: 生成并显示整数列表 C#: 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用系统文本; 使用System.Windows; 使用System.Windows.Controls; 使用System.Windows.Data; 使用System.Wi

我在自学C#,OOP和WPF,所以这些东西的潜力是惊人的

因此,有人能解释一下为什么在我的小测试示例中单击按钮后,Name属性出现在文本框中,而ListBox没有显示任何内容吗

XAML:

生成并显示整数列表

C#:
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
命名空间绑定测试
{
/// 
///Window1.xaml的交互逻辑
/// 
公共部分类Window1:Window
{
公共窗口1()
{
初始化组件();
}
私有void MakeIntListButton_单击(对象发送者,路由目标)
{
AClass instanceofclass=new AClass();
instanceofclass.MyIntegers.Add(6);
InstanceOfAClass.MyIntegers.Add(7);
instanceofclass.MyIntegers.Add(42);
instanceofclass.Name=“Fred”;
mainGrid.DataContext=instanceofclass;
}
}
公共类AClass
{
公共字符串名称{get;set;}
public List MyIntegers=new List();
}
}

我怀疑这是否与“MyIntegers”是公共字段而不是属性这一事实有关。你能把你的类重构成这样并尝试一下吗

public class AClass
{
    private List<int> _ints = new List<int>();

    public string Name { get; set; }
    public List<int> MyIntegers
    {
        get { return _ints; }
    }
}
公共类AClass
{
私有列表_ints=新列表();
公共字符串名称{get;set;}
公共列表整数
{
获取{return\u ints;}
}
}

我运行了您的示例,当我单击按钮时,文本框中填充了预期的名称

我遇到的唯一问题是ListView没有填充整数列表。这与这样一个事实有关:如果将XAML修改为绑定到一个数组,那么它对泛型不是很适应。WPF支持XAML的使用,但它在XAML中使用了不受支持的泛型。正如马特·汉密尔顿在他的回答中指出的那样,我的整数只需要通过添加一个get acessor就可以成为一个属性

添加C#属性:

public int[] MyInts { get { return MyIntegers.ToArray(); } } 
XAML:



研究如何使用System.Collections.ObjectModel.ObservableCollection进行列表绑定,而不是使用普通列表。

XAML和数据绑定与泛型配合良好——ObservableCollection是WPF中列表绑定的基石!为了绑定到泛型集合,完全不需要将泛型集合转换为数组。是的,您是对的。我在XAML()中直接混淆了泛型支持,而不是使用它。感谢sipwiz,它确实有效,但可能是因为我们现在绑定到的是属性而不是字段。谢谢Matt。这让我困惑了好几个小时。那时我们都学到了一些东西!我不知道WPF不会绑定到这样的公共字段。我得好好读一读!
public class AClass
{
    private List<int> _ints = new List<int>();

    public string Name { get; set; }
    public List<int> MyIntegers
    {
        get { return _ints; }
    }
}
public int[] MyInts { get { return MyIntegers.ToArray(); } } 
<ListBox Grid.Row="2" ItemsSource="{Binding Path=MyInts}" />