XAML 繫結和結構體不得不說的問題
阿新 • • 發佈:2018-12-24
遇見一個問題
如果用一個結構體struct。再用一個ListView,然後使用繫結。
<Window x:Class="WpfApp1.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:mcView Code="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <DataTemplate x:Key="ItemProjectTemplate"> <StackPanel> <Image Source="img/1.jpg"Width="50" Height="50" /> <TextBlock FontSize="22" Text="{Binding Name}" /> </StackPanel> </DataTemplate> </Window.Resources> <ListView HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="423"x:Name="Projects" ItemTemplate="{StaticResource ItemProjectTemplate}"/> </Window>
using System.Windows; namespace WpfApp1 { public struct Project { public string Name; } /// <summary> /// MainWindow.xaml 的互動邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Projects.ItemsSource = InitProject(); } private Project[] InitProject() { Project[] x = new Project[3]; x[0].Name = "1"; x[1].Name = "2"; x[2].Name = "3"; return x; } } }View Code
看一看效果
會發現圖片加載出來了,可是繫結的文字資料不見了~
在https://stackoverflow.com/questions/13101449/xaml-binding-code-not-working有這樣的答覆
DataBinding works for Properties and not on Fields. Replace Struct with class and make your fields as properties-
因為結構體裡面是欄位不是屬性,所以就沒有作用了。需要改寫成
public struct Project { public string Name { get; set; } }
這樣就顯示正常了