我是WPF的新手,所以我嘗試了一些教程。現在在我的第二個項目有一些東西讓我瘋狂......C#WPF數據綁定 - 爲什麼WPF顯示單個字母而不是列表的內容
這裏是C#代碼:
using System.Windows;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace WpfDataBindingTest1
{
public partial class MainWindow : Window
{
private ICollection<TestClass> testClassCollection;
public ICollection<TestClass> TestClassCollection
{
get { return this.testClassCollection; }
set { if (this.testClassCollection != value) { this.testClassCollection = value; } }
}
public MainWindow()
{
InitializeComponent();
this.testClassCollection = new ObservableCollection<TestClass>()
{
new TestClass() {ID = 1, Name = "Name1" },
new TestClass() {ID = 2, Name = "Name2" },
new TestClass() {ID = 3, Name = "Name3" }
};
}
}
public class TestClass
{
public int ID { get; set; }
public string Name { get; set; }
}
}
這裏是XAML代碼:
<Window x:Class="WpfDataBindingTest1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfDataBindingTest1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox
x:Name="lbTestClassItems"
ItemsSource="{Binding Source=TestClassCollection}">
</ListBox>
</Grid>
</Window>
所以,編譯時和運行這個,我只在XAML文件中定義的列表框的一個新行中顯示Word的每個字母「TestClassCollection」。
在定義列表框的時候添加DisplayMemberPath="ID"
時,什麼也沒有顯示。
一些搜索後,我發現這一點:why is it displaying class name instead of property?
但這並沒有幫助。
編輯:神祕如果我通過代碼(設置itemsource和DisplayMemberPath),它顯示正確的數據。但如果我通過XAML進行操作,請參閱上面的
在此先感謝!
爲什麼你在'ItemsSource'中使用'Source'而不是'Path'? – rbr94
你必須使用正確的'ItemTemplate'。列表框本身並不知道你的裝訂項目應該如何顯示 – lokusking
@ rbr94:同樣的結果,沒有任何顯示 – Radinator