2014-03-05 87 views
0

我有以下WPF XAML:爲什麼我的數據綁定WPF列表框顯示行?

<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

您需要設置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 
相關問題