Dynamically creating WrapPanel buttons

瘦欲@ 提交于 2020-01-15 11:47:06

问题


I have a table storing purchased items and the entity class using in NHibernate:

public class PurchasedItem
{
    public virtual int Id          { get; set; }
    public virtual Product Product { get; set; }
    public virtual int SortSale    { get; set; }
}

I would like to reduce the code duplication by getting all records from the PurchasedItems table (IList <PurchasedItem> object). Records have been sorted in descending order by SortSale column. What's the best way of creating WrapPanel buttons based on the IList <PurchasedItem> object? I would like to assign the event handler for each button as well. The button displays a title with the name of the product.


回答1:


You'll need to create a listbox using a WrapPanel as the ItemsPanel. In XAML you can do the following:

<ListBox Name="MyList" ItemsSource={StaticResource YourList}>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button Height="40" MinWidth="40" Content="{Binding Id}" Click="Button_Click"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

In this example, I assume YourList is a list of PurchasedItem's. You can also set the ItemsSource from code (ie: MyList.ItemsSource = YourList;). When you click the Button, it'll call the following which can display a messagebox containing whatever you need:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(((sender as Button).DataContext as PurchasedItem).Product.Name);
    }

Note that I set the Content of the Button to the Id of the PurchasedItem so you'll probably want to change that.



来源:https://stackoverflow.com/questions/2766875/dynamically-creating-wrappanel-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!