为什么我的数据绑定WPF ListBox不显示行?

时间:2014-03-05 20:22:38

标签: c# .net wpf xaml binding

我有以下WPF XAML:

<Window x:Class="ListBoxTesting.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <ListBox Name="ListBoxOne" Grid.Row="0" ItemsSource="{Binding ListOne}" DisplayMemberPath="NameOne"/>
        <ListBox Name="ListBoxTwo" Grid.Row="1" ItemsSource="{Binding ListTwo}" DisplayMemberPath="NameTwo"/>
    </Grid>
</Window>

使用此代码:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 ListBoxTesting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public class TypeOne
        {
            public string NameOne { get; set; }

            public TypeOne(string name)
            {
                NameOne = name;
            }
        }

        public class TypeTwo
        {
            public string NameTwo { get; set; }

            public TypeTwo(string name)
            {
                NameTwo = name;
            }
        }

        public ObservableCollection<TypeOne> ListOne { get; set; }
        public ObservableCollection<TypeTwo> ListTwo { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            ListOne = new ObservableCollection<TypeOne>();
            ListOne.Add(new TypeOne("Mike"));
            ListOne.Add(new TypeOne("Bobby"));
            ListOne.Add(new TypeOne("Joe"));
            ListTwo = new ObservableCollection<TypeTwo>();
            ListTwo.Add(new TypeTwo("Mike"));
            ListTwo.Add(new TypeTwo("Bobby"));
            ListTwo.Add(new TypeTwo("Joe"));
        }
    }
}

但是出于某种原因,一旦我在调试模式下启动项目,我就无法在UI中看到任何行。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要将DataContext设置为后面的代码来解决绑定:

可能在代码

之后
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this; <--- HERE
        .....
    }

XAML

<Window x:Class="ListBoxTesting.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"> <-- HERE