How to add multiple new buttons from template in a UI from C# and call on click event for a particular buttons

前端 未结 2 1456
自闭症患者
自闭症患者 2020-12-22 12:21

I am reading a database file and based on the no. of entries output from the database to my query, I want to populate the buttons. And on clicking any of these buttons, I wa

相关标签:
2条回答
  • 2020-12-22 12:58

    The task of generating multiple controls for multiple items from some list is best solved using ItemsControl:

    <ItemsControl Name="itemsList">
        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="local:DataEntity">
                <Button Template="{StaticResource RoundBtn}" 
                        Content="{Binding Name}"
                        Click="ItemButtonClick"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    This ItemsControl named "itemsList" contains buttons with custom template. Each button will display one the Name of one item from list.

    DataEntity is a class which contains values from db, e.g.

    public class DataEntity
    {
        public string Name { get; set; }
    }
    

    Items list is linked to ItemsControl via ItemsSource property (in my demo I'm doing it in window code-behind in constructor)

    itemsList.ItemsSource = new ObservableCollection<DataEntity>
    {
        new DataEntity { Name = "A" },
        new DataEntity { Name = "B" },
        new DataEntity { Name = "C" },
    };
    

    Buttons have click handler attached ("ItemButtonClick"). The clicked button is determined from sender argument:

    private void ItemButtonClick(object sender, RoutedEventArgs e)
    {
        var button = (Button)sender;
        var item = button.DataContext as DataEntity;
    
        MessageBox.Show("Clicked " + item.Name);
    }
    
    0 讨论(0)
  • 2020-12-22 13:11

    Rather than creating a ControlTemplate,just create a Style.Then the code would be like :

     Button btn = new Button
     btn.Style= (Style)FindResource("RoundBtn")
     grid.Children.Add(btn);
     btn.click += new EventHandler(btn_click);
    
     private void btn_Click(object sender, RoutedEventArgs e)
    {
     }
    
    0 讨论(0)
提交回复
热议问题