遇见一个问题
如果用一个结构体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:mc="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; } } }
看一看效果
会发现图片加载出来了,可是绑定的文本数据不见了~
在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; } }
这样就显示正常了
或者有更加高端的做法,用一个转化器
using System; using System.Globalization; using System.Windows.Data; namespace WpfApp1 { public class Name : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is Project project) { var name = project.Name; return name; } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
<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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800" xmlns:convert="clr-namespace:WpfApp1"> <Window.Resources> <convert:Name x:Key="Name"/> <DataTemplate x:Key="ItemProjectTemplate"> <StackPanel> <Image Source="img/1.jpg" Width="50" Height="50" /> <TextBlock FontSize="22" Text="{Binding Converter={StaticResource Name}}" /> </StackPanel> </DataTemplate> </Window.Resources> <ListView HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="423" x:Name="Projects" ItemTemplate="{StaticResource ItemProjectTemplate}"/> </Window>