Datatemplate
这是为 WPF创建自定义的一个非常基本的示例。
首先,您Model
使用要显示的所有属性创建您的,然后将它们的列表绑定到您的ListBox
. 然后你可以创建一个DataTemplate
这基本上是你的 xaml(visual) 表示Model
,你可以让它看起来像你想要的那样,你可以Model
使用DataTemplate
.
例子:
窗口代码:
public partial class MainWindow : Window
{
private ObservableCollection<MyListBoxItemModel> _listBoxItems = new ObservableCollection<MyListBoxItemModel>();
public MainWindow()
{
InitializeComponent();
ListBoxItems.Add(new MyListBoxItemModel { Title = "Item 1", Image = new BitmapImage(new Uri("http://icons.iconarchive.com/icons/custom-icon-design/mini/32/Search-icon.png")) });
ListBoxItems.Add(new MyListBoxItemModel { Title = "Item 2", Image = new BitmapImage(new Uri("http://icons.iconarchive.com/icons/custom-icon-design/mini/32/Search-icon.png")) });
ListBoxItems.Add(new MyListBoxItemModel { Title = "Item 3", Image = new BitmapImage(new Uri("http://icons.iconarchive.com/icons/custom-icon-design/mini/32/Search-icon.png")) });
}
public ObservableCollection<MyListBoxItemModel> ListBoxItems
{
get { return _listBoxItems; }
set { _listBoxItems = value; }
}
}
模型:
public class MyListBoxItemModel : INotifyPropertyChanged
{
private string _title;
private string _line2 = "Line2";
private BitmapImage _image;
public string Title
{
get { return _title; }
set { _title = value; NotifyPropertyChanged("Title"); }
}
public string Line2
{
get { return _line2; }
set { _line2 = value; NotifyPropertyChanged("Line2"); }
}
public BitmapImage Image
{
get { return _image; }
set { _image = value; NotifyPropertyChanged("Image"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
}
xml:
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication7"
Title="MainWindow" Height="351" Width="464" Name="UI" >
<Window.Resources>
<!-- The tempate for MyListBoxItemModel -->
<DataTemplate DataType="{x:Type local:MyListBoxItemModel}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Image}" />
<StackPanel>
<TextBlock Text="{Binding Title}" FontWeight="Medium" />
<TextBlock Text="{Binding Line2}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding ElementName=UI, Path=ListBoxItems}" />
</Grid>
</Window>
这只是一个带有Image
和一些文本的简单示例,但它应该可以帮助您入门,只需修改DataTemplate
以及Model
您希望如何显示snp code
数据
结果: