WPF —ListView用ItemsSource繫結物件列表
阿新 • • 發佈:2019-01-05
雖然wpf 開發有段時間了,但是對於繫結資料這塊兒,理解的還是不太深入 。
xaml
<ListView Canvas.Left="59" Canvas.Top="170" Height="253" Name="listView1" Width="714" > <span style="white-space:pre"> </span><ListView.ItemTemplate> <span style="white-space:pre"> </span><DataTemplate> <span style="white-space:pre"> </span><Canvas Width="710" Height="30" Background="{Binding Path=background}" > <span style="white-space:pre"> </span><Rectangle Canvas.Left="15" Canvas.Top="7" Name="rectangle51" Style="{StaticResource RectangleLocked}" > <span style="white-space:pre"> </span><Rectangle.Fill> <span style="white-space:pre"> </span><ImageBrush ImageSource="{Binding Path=imgSource}" /> <span style="white-space:pre"> </span></Rectangle.Fill> <span style="white-space:pre"> </span></Rectangle> <span style="white-space:pre"> </span><Label Canvas.Left="234" Canvas.Top="2" Content="{Binding Path=roomName}" Name="label7" Style="{StaticResource LabelItem}" Width="107" /> <span style="white-space:pre"> </span><Label Canvas.Left="357" Canvas.Top="2" Content="{Binding Path=createrName}" Name="label8" Style="{StaticResource LabelItem}" Width="107" /> <span style="white-space:pre"> </span><Label Canvas.Left="476" Canvas.Top="1" Content="{Binding Path=roomState}" Name="label9" Style="{StaticResource LabelItem}" Width="72" /> <span style="white-space:pre"> </span><Label Canvas.Left="558" Canvas.Top="2" Content="{Binding Path=howmany}" Name="label10" Style="{StaticResource LabelItem}" Width="72" /> <span style="white-space:pre"> </span></Canvas> <span style="white-space:pre"> </span></DataTemplate> <span style="white-space:pre"> </span></ListView.ItemTemplate> </ListView>
樣式就不貼了,隨意。
程式碼:
public class Room { public string imgSource { set; get; } public string createrName { set; get; } public string roomName { set; get; } public string roomState { set; get; } public string howmany { set; get; } public string rowBg { set; get; } public ImageBrush background { set; get; } }
//初始化物件列表,
List<Room> roomList = new List<Room>(); for (int i = 0; i < 15; i++) { var newitem = new Room() { //rowBg = "images/row_background.png", imgSource = "images/locked.png", roomName = "room_" + i, createrName = "name_" + i, roomState = "sate--" + i, howmany = "人數_" + i*10, }; ImageBrush b = new ImageBrush(); b.ImageSource = new BitmapImage(new Uri(new FileInfo("images/row_background.png").FullName, UriKind.Absolute)); b.Stretch = Stretch.Fill; newitem.background = b; roomList.Add(newitem); } listView1.ItemsSource = roomList;
結果