
当我们需要用到循环的列表内容,并且模板化程度高的时候,建议使用 ListBox 来做绑定。
XAML:
<Window.DataContext>
<local:VMTempTest/>
</Window.DataContext>
<StackPanel Margin="10,0,0,50" Orientation="Vertical" >
<TextBlock Text="ListBox 模板" FontWeight="Bold" Margin="0,5,0,5" ></TextBlock>
<DockPanel >
<StackPanel HorizontalAlignment="Left" DockPanel.Dock="Top" >
<ListBox x:Name="lb" ItemsSource="{Binding ListBoxData}" BorderThickness="0" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Width="{Binding ActualWidth,RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding Img}" Width="96" Height="96"/>
<TextBlock HorizontalAlignment="Center" FontSize="16" Text="{Binding Info}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
<StackPanel DockPanel.Dock="Bottom" DataContext="{Binding SelectedItem,ElementName=lb}" Margin="15 30 0 0" HorizontalAlignment="Left" Orientation="Vertical" >
<TextBlock Text="{Binding Info,StringFormat='选中:\{0\}'}" ></TextBlock>
</StackPanel>
</DockPanel>
</StackPanel>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
ViewModel:
public class VMTempTest : ViewModelBase
{
public VMTempTest()
{
ListBoxData = new ObservableCollection<dynamic>(){
new { Img="/MyWpfApp;component/Images/1.jpg",Info="樱桃" },
new { Img="/MyWpfApp;component/Images/2.jpg",Info="葡萄" },
new { Img="/MyWpfApp;component/Images/3.jpg",Info="苹果" },
new { Img="/MyWpfApp;component/Images/4.jpg",Info="猕猴桃" },
new { Img="/MyWpfApp;component/Images/5.jpg",Info="柠檬" },
};
}
private IEnumerable listBoxData;
public IEnumerable ListBoxData
{
get { return listBoxData; }
set { listBoxData = value; RaisePropertyChanged(() => ListBoxData); }
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2016-08-18 【转】C# 中的委托和事件
2016-08-18 你知道C#中的Lambda表达式的演化过程吗