从ViewModel添加Usercontrol作为ListBoxItem

时间:2015-01-15 19:34:55

标签: wpf mvvm

我是MVVM(和WPF)的新手。我有一个主视图,它有一个ListBox,添加了相同的usercontrol x次。添加这些控件没有问题。 UC包含一个ListBox,它将包含未知数量的项目。这些物品可以是另一个UC吗?我如何不破坏MVVM并将项目添加到每个UC添加的ListBox中?

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

您可以在列表框的ItemTemplate中的Datatemplate中添加usercontrol。参考以下样本。

<Window x:Class="MSDN15Jan2015_Learning.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MSDN15Jan2015_Learning"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ListBox ItemsSource="{Binding PersonList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <local:ListBoxItemControl/> 
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();
    }
}
 class MainViewModel
{
    private ObservableCollection<Person> perList = new ObservableCollection<Person>();

    public ObservableCollection<Person> PersonList 
    {
        get { return perList; }
        set { perList = value; }
    }


    public MainViewModel()
    {
        perList.Add(new Person() { Age = 1, Name = "Test1"});
        perList.Add(new Person() { Age = 2, Name = "Test2" });
        perList.Add(new Person() { Age = 3, Name = "Test3" });
        perList.Add(new Person() { Age = 4, Name = "Test4" });
    }
}

public class Person
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}
<UserControl x:Class="MSDN15Jan2015_Learning.ListBoxItemControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <StackPanel>
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding Age}"/>
    </StackPanel>
</Grid>