How to make custom control with ListBox?

前端 未结 1 329
傲寒
傲寒 2021-01-17 07:09

\"enter

I want to make horizontal ListBox with customized item template, so I make a b

相关标签:
1条回答
  • 2021-01-17 07:49

    Let's say we have a basic class named Item:

    public class Item : INotifyPropertyChanged
    {
        public string Text { get; set; } // Implement INotifyPropertyChanged 
        public string ImagePath { get; set; } // properly on these properties
    }
    

    And a collection of these in a view model:

    public ObservableCollection<Item> Items { get; set; } 
    

    Now to display these items in the UI, we use a ListBox and set the ItemsSource property:

    <ListBox ItemsSource="{Binding Items}">
    </ListBox>
    

    When it comes to defining the ListBox.ItemTemplate, you need to understand that this DataTemplate will be applied to each item and that it has access to all of the properties defined in the Item class:

    <ListBox ItemsSource="{Binding Items}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <Image ImageSource="{Binding ImagePath}" />
                    <TextBlock Text="{Binding Text}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    Therefore, you can access the properties in the collection class as shown above. You can find out the full story by looking at the ItemsControl.ItemTemplate Property page on MSDN.

    0 讨论(0)
提交回复
热议问题