简体   繁体   English

动态创建WrapPanel按钮

[英]Dynamically creating WrapPanel buttons

I have a table storing purchased items and the entity class using in NHibernate: 我有一个表存储购买的项目和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). 我想通过从PurchasedItems表( IList <PurchasedItem>对象)获取所有记录来减少代码重复。 Records have been sorted in descending order by SortSale column. 记录按SortSale列按降序排序。 What's the best way of creating WrapPanel buttons based on the IList <PurchasedItem> object? 基于IList <PurchasedItem>对象创建WrapPanel按钮的最佳方法是什么? I would like to assign the event handler for each button as well. 我也想为每个按钮分配事件处理程序。 The button displays a title with the name of the product. 该按钮显示带有产品名称的标题。

You'll need to create a listbox using a WrapPanel as the ItemsPanel. 您需要使用WrapPanel作为ItemsPanel创建列表框。 In XAML you can do the following: 在XAML中,您可以执行以下操作:

<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. 在此示例中,我假设YourList是PurchasedItem的列表。 You can also set the ItemsSource from code (ie: MyList.ItemsSource = YourList;). 您还可以从代码中设置ItemsSource(即: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. 请注意,我将Button的内容设置为PurchasedItem的Id,因此您可能希望更改它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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