简体   繁体   中英

Collection property for WPF UserControl

I want to create a UserControl in WPF through which I want to expose a collection property. I want to change the UI of the UserControl based on the changes in collection.

For example, lets say I have a collection of strings which is binded to my UserControl . Based on that collection i want to create buttons on the UserControl containing those text as button text. Is there a way I can acieve this?

Yes, you can set a DataTemplate containing a button for an ItemsControl control that is binded to that collection. For Example:

//For code:
items.DataContext = new List<string>
{
    "Item 1",
    "Item 2",
    "Item 3"
};

//For XAML            
<ItemsControl x:Name="items" ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM