问题
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