我在我的 XAML 中定义了两个 ListBox 和一个 MyListItem 类。现在,第一个 ListBox 应将名称显示为按钮,第二个 ListBox 应将名称显示为 TextBlock。
这是一个小例子,两个 ListBox 的行为相同。
我的列表项
public class MyListItem
{
private string _name;
public string Name
{
get{return _name;}
set{_name = value;}
}
}
XAML
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataTemplate.Views.MainWindow"
xmlns:viewsmodels="clr-namespace:DataTemplate.ViewModels;assembly=DataTemplate"
xmlns:dt="clr-namespace:DataTemplate;assembly=DataTemplate"
Title="DataTemplate" Width="700">
<Window.DataContext>
<viewsmodels:MainWindowViewModel />
</Window.DataContext>
<Grid ColumnDefinitions="250,250,250">
<ItemsControl Grid.Column="1" Items="{Binding List2}">
<ItemsControl.DataTemplates>
<DataTemplate DataType="{x:Type dt:MyListItem}">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ItemsControl.DataTemplates>
</ItemsControl>
<ItemsControl Grid.Column="2" Items="{Binding List3}">
<ItemsControl.DataTemplates>
<DataTemplate DataType="{x:Type dt:MyListItem}">
<Button Content="{Binding Name}"/>
</DataTemplate>
</ItemsControl.DataTemplates>
</ItemsControl>
</Grid>
</Window>
视图模式
public class MainWindowViewModel
{
public ObservableCollection<MyListItem> List1 { get; set; }
public ObservableCollection<MyListItem> List2 { get; set; }
public ObservableCollection<MyListItem> List3 { get; set; }
public MainWindowViewModel()
{
List1 = new ObservableCollection<MyListItem>();
List2 = new ObservableCollection<MyListItem>();
List3 = new ObservableCollection<MyListItem>();
Random rand = new Random();
for (int i = 0; i < rand.Next(1, 20); i++)
{
MyListItem mli = new MyListItem();
mli.Name = "ListItem" + i;
List1.Add(mli);
}
for (int i = 0; i < rand.Next(1, 20); i++)
{
MyListItem mli = new MyListItem();
mli.Name = "ListItem" + i;
List2.Add(mli);
}
for (int i = 0; i < rand.Next(1, 20); i++)
{
MyListItem mli = new MyListItem();
mli.Name = "ListItem" + i;
List3.Add(mli);
}
}
}