c# - 如何使用 DataContext 绑定(bind)到 List<T>?

标签 c# .net wpf xaml

我正在自学 C#、OOP 和 WPF,因此学习的潜力是惊人的。

因此,有人可以解释一下为什么在我的小测试示例中单击按钮后,Name 属性出现在 TextBox 中,但 ListBox 没有显示任何内容?

XAML:

<Window x:Class="BindingTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BindingTest" Height="250" Width="300">
<Grid Name="mainGrid">
    <Grid.RowDefinitions>
        <RowDefinition Height="50" />
        <RowDefinition Height="50" />
        <RowDefinition Height="100" />
    </Grid.RowDefinitions>
    <Button 
            Grid.Row="0"
            Name="MakeIntListButton"
            Click="MakeIntListButton_Click">Make and Display Integer List</Button>
    <TextBox Grid.Row="1" Text ="{Binding Path=Name}"
             />
    <ListBox
        Grid.Row="2"
        ItemsSource="{Binding Path=MyIntegers}"
        />
</Grid>

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BindingTest
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void MakeIntListButton_Click(object sender, RoutedEventArgs e)
        {
            AClass InstanceOfAClass = new AClass();
            InstanceOfAClass.MyIntegers.Add(6);
            InstanceOfAClass.MyIntegers.Add(7);
            InstanceOfAClass.MyIntegers.Add(42);

            InstanceOfAClass.Name = "Fred";


            mainGrid.DataContext =InstanceOfAClass ;
        }
    }

    public class AClass
    {
        public string Name {get;set;}
        public List<int> MyIntegers = new List<int>();
    }
}

最佳答案

我想知道这是否与“MyIntegers”是公共(public)字段而不是属性这一事实有关。您可以将您的类重构为如下所示并尝试一下吗?

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

    public string Name { get; set; }
    public List<int> MyIntegers
    {
        get { return _ints; }
    }
}

关于c# - 如何使用 DataContext 绑定(bind)到 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/745970/

相关文章:

c# - 使用 Selenium 使用 WindowHandles 跟踪和迭代选项卡和窗口的最佳方法

c# - 如何跟踪 ASP.NET MVC 应用程序的性能问题?

c# - 当 ExecuteScalar 工作正常时,为什么 ExecuteReader 会崩溃读取某些记录的特定数据字段?

c# - 在组合框中的 XAML 中设置默认值

wpf - WPF错误处理多语言

c# - 由于代码契约(Contract),ASP NET WebApp 在发布后失败

c# - C# 中的日期时间格式

c# - Texture2D.GetData() 返回不同的数据

c# - Microsoft Code Contracts 和 CI 构建服务器

wpf - 从 WPF 中的 ViewModel 类(MVVM 模式)更新 UI