[英]Dynamically add multiple buttons to wpf window?
我如何將多個按鈕添加到 c# 中的窗口? 這是我需要做的...我從字典中獲取多個用戶值(在合理范圍內,只有@ 5-6 個值)。 對於每個值,我需要創建一個按鈕。 現在,我如何命名按鈕,而不是按鈕內的文本? 我如何為每個按鈕定義“點擊”方法(它們都會不同)? 如果我不再想要它,我該如何擦除按鈕?
我會把整個事情都封裝起來,通常沒有必要給按鈕命名。 像這樣的東西:
public class SomeDataModel
{
public string Content { get; }
public ICommand Command { get; }
public SomeDataModel(string content, ICommand command)
{
Content = content;
Command = command;
}
}
然后你可以創建模型並將它們放入一個可綁定的集合中:
public ObservableCollection<SomeDataModel> MyData { get; } =
new ObservableCollection<SomeDataModel>();
然后你只需要添加和刪除項目並動態創建按鈕:
<ItemsControl ItemsSource="{Binding MyData}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Content}" Command="{Binding Command}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
有關更多信息,請參閱 MSDN 上的相關文章:
考慮您有一個名為 sp 的StackPanel
for(int i=0; i<5; i++)
{
System.Windows.Controls.Button newBtn = new Button();
newBtn.Content = i.ToString();
newBtn.Name = "Button" + i.ToString();
sp.Children.Add(newBtn);
}
要刪除按鈕,你可以做
sp.Children.Remove((UIElement)this.FindName("Button0"));
希望這有幫助。
Xml代碼:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<UniformGrid x:Name="grid">
</UniformGrid>
</Window>
代碼隱藏:
public MainWindow()
{
InitializeComponent();
for (int i = 0; i < 10; ++i)
{
Button button = new Button()
{
Content = string.Format("Button for {0}", i),
Tag = i
};
button.Click += new RoutedEventHandler(button_Click);
this.grid.Children.Add(button);
}
}
void button_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine(string.Format("You clicked on the {0}. button.", (sender as Button).Tag));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.