动态创建WrapPanel按钮 [英] Dynamically creating WrapPanel buttons
问题描述
我有一个表,用于存储购买的物品和NHibernate中使用的实体类:
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; }
}
我想通过从PurchasedItems
表(IList <PurchasedItem>
对象)获取所有记录来减少代码重复.记录已按SortSale
列按降序排序.基于IList <PurchasedItem>
对象创建WrapPanel
按钮的最佳方法是什么?我也想为每个按钮分配事件处理程序.该按钮显示带有产品名称的标题.
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.
推荐答案
您需要使用WrapPanel作为ItemsPanel创建一个列表框.在XAML中,您可以执行以下操作:
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>
在此示例中,我假设YourList是PurchasedItem的列表.您还可以从代码中设置ItemsSource(即:MyList.ItemsSource = YourList;).当您单击按钮时,它将调用以下内容,该内容将显示一个包含所需内容的消息框:
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);
}
请注意,我将按钮的内容设置为PurchasedItem的ID,因此您可能需要更改它.
Note that I set the Content of the Button to the Id of the PurchasedItem so you'll probably want to change that.
这篇关于动态创建WrapPanel按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!