开发者

Dynamically creating WrapPanel buttons

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 b开发者_Python百科y 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜