在WPF的ListBox中根据数据自定义Item的位置

来源:转载

 话说,包包想在游戏大厅里实现只操作数据源就能更新绑定控件的需求。OK,你一定会说,用ListBox。没错,ListBox就是干这个用的:
  
  以下是xaml和后台代码:
  
  <UserControl x:Class="TestDeskBindingWpfApplication.PaneDesk"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:TestDeskBindingWpfApplication"
   Height="160" Width="160">
   <UserControl.Resources>
   <Style TargetType="{x:Type Image}" x:Key="desk" />
   <local:ImageConverter x:Key="imageConverter" />
   <local:HandConverter x:Key="handConverter" />
   <local:LeftConverter x:Key="leftConverter" />
   <local:TopConverter x:Key="topConverter" />
  
   <DataTemplate DataType="{x:Type local:UserInfo}">
   <TextBlock>
   <Image Canvas.Left="60" Canvas.Top="3" Name="chair"
   Source="{Binding Path=ImageIndex, Converter={StaticResource imageConverter},
   Mode=TwoWay, NotifyOnTargetUpdated=True}" />
   <Image Canvas.Left="86" Canvas.Top="53" Name="hand" Source="Img/hand.gif"
   Visibility="{Binding Path=IsPrepareOK, Converter={StaticResource handConverter},
   Mode=TwoWay, NotifyOnTargetUpdated=True}" />
   <Label Name="lblUser" Width="54"
   Canvas.Left="{Binding Path=DeskPosition, Converter={StaticResource leftConverter}}"
   Canvas.Top="{Binding Path=DeskPosition, Converter={StaticResource topConverter}}"
   Content="{Binding Path=UserName, Mode=TwoWay, NotifyOnTargetUpdated=True}" />
   </TextBlock>
   </DataTemplate>
   </UserControl.Resources>
   <Canvas Background="#FF28699E">
   <ListBox Canvas.Left="0" Canvas.Top="0" Height="160" x:Name="r1" Width="160" />
   </Canvas>
  
  </UserControl>
  
  
  相应数据源代码:
  
  public ObservableCollection<UserInfo> Users = new ObservableCollection<UserInfo>();
   UserInfo user = null;
  
  user = new UserInfo { UserId = 2, UserName = "kitty", DeskId = 1, DeskPosition = 1, ImageIndex = 4, IsPrepareOK = true };
  Users.Add(user);
  user = new UserInfo { UserId = 1, UserName = "jax", DeskId = 1, DeskPosition = 2, ImageIndex = 3 };
  Users.Add(user);
  user = new UserInfo { UserId = 4, UserName = "dx", DeskId = 1, DeskPosition = 3, ImageIndex = 1 };
  Users.Add(user);
  user = new UserInfo { UserId = 3, UserName = "jeffrey", DeskId = 1, DeskPosition = 4, ImageIndex = 4 };
  Users.Add(user);
  
  r1.ItemsSource = Users;
  这样做的好处是,以后我只需要Users.Add(newUser)或Users.Remove(oldUser)就可以同时控制桌子上显示的用户了。
  
  但是,我要说,我想在桌子里实现这样的效果:
  
  就是说,对号入座,将ListBox中的每个Item都能自定义它的定位,但遗憾的是,

[1] [2] 下一页

分享给朋友:
您可能感兴趣的文章:
随机阅读: