当我们需要用到循环的列表内容,并且模板化程度高的时候,建议使用 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
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;
/// <summary>
/// LisBox数据模板
/// </summary>
public IEnumerable ListBoxData
{
get { return listBoxData; }
set { listBoxData = value; RaisePropertyChanged(() => ListBoxData); }
}
}
标签:Info,控件,Img,MyWpfApp,component,Binding,jpg,new,WPF
From: https://www.cnblogs.com/webenh/p/17640215.html