在學習深入淺出WPF第六章節Binding,敲寫TextBox綁定List列表案例時,怎麼也不能達到書上的效果,後來發現,書上的代碼案例給錯了。哎,這回記憶深刻了。特此寫博客記錄下。好了上代碼。
xmal代碼如下:
<Window x:Class="ListTest.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:ListTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid>
<StackPanel Margin="10,10,12,12" Name="stackPanel1">
<TextBox Height="23" Margin="10" Name="textBox1" Width="120" />
<TextBox Height="23" Margin="10" Name="textBox2" Width="120" />
<TextBox Height="23" Margin="10" Name="textBox3" Width="120" />
</StackPanel>
</Grid>
</Grid>
</Window>
.cs代碼如下:
using System;
using System.Collections.Generic;
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 ListTest
{
/// <summary>
/// MainWindow.xaml 的交互邏輯
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Country> countryList = new List<Country>
{ new Country()
{
Name = "中國",
ProvinceList = new List<Province>()
{ new Province()
{
Name = "四川",
CityList = new List<City>()
{ new City()
{ Name = "成都" }
}
}
}
}
};
this.textBox1.SetBinding(TextBox.TextProperty, new Binding("/Name") { Source = countryList });
this.textBox2.SetBinding(TextBox.TextProperty, new Binding("/ProvinceList/Name") { Source = countryList });
this.textBox3.SetBinding(TextBox.TextProperty, new Binding("/ProvinceList/CityList/Name") { Source = countryList });
Console.WriteLine(countryList[0].Name);
Console.WriteLine(countryList[0].ProvinceList[0].Name);
Console.WriteLine(countryList[0].ProvinceList[0].CityList[0].Name);
}
}
class City
{
public string Name { get; set; }
}
class Province
{
public string Name { get; set; }
public List<City> CityList { get; set; }
}
class Country
{
public string Name { get; set; }
public List<Province> ProvinceList { get; set; }
}
}
運行結果:
目的是textBox1綁定countryList[0].Name。
textBox2綁定countryList[0].ProvinceList[0].Name。
textBox3綁定countryList[0].ProvinceList[0].CityList[0].Name。
實際上“/”就是獲取下一子集合。
這是正確的結果。書上錯誤的案例是這麼寫的:
this.textBox1.SetBinding(TextBox.TextProperty, new Binding("/Name") { Source = countryList });
this.textBox2.SetBinding(TextBox.TextProperty, new Binding("/ProvinceList.Name") { Source = countryList });
this.textBox3.SetBinding(TextBox.TextProperty, new Binding("/ProvinceList/CityList.Name") { Source = countryList });
把/ProvinceList.Name 換成/ProvinceList/Name就可以了。
案例出自深入淺出WPF第91頁。