Two different DataTemplate

Viewed 1457

I have two ListBoxs defined in my XAML and one Class MyListItem. Now one ListBox should display the name as button and the second ListBox should display the name as a TextBlock.

Here a little example, both ListBoxs behave the same.

MyListItem

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>

ViewMode

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);
        }
    }
}
2 Answers
Related