[英]Programmatically add buttons to a UWP app
Suppose my app has one button that adds another button. 假设我的应用程序有一个按钮,可以添加另一个按钮。 If I press it, another button should appear right next to the first button.
如果我按下它,第一个按钮旁边会出现另一个按钮。 Also, the new button should become the "add a new button"-button.
此外,新按钮应该成为“添加新按钮”按钮。
How do I do this? 我该怎么做呢?
My approach was creating a RelativePanel, because in the Editor, you can say "Place this left of that". 我的方法是创建一个RelativePanel,因为在编辑器中,你可以说“放置它的左边”。 However, it can't find a way to do that in C# code.
但是,它无法在C#代码中找到一种方法。
You can follow ctron's comment and do it via setting attached property value in the code. 您可以关注ctron的评论 ,并通过在代码中设置附加属性值来完成。 The sample can look like this - XAML:
样本看起来像这样 - XAML:
<RelativePanel x:Name="myPanel" Margin="100">
<Button Content="StartBtn" Click="Button_Click"/>
</RelativePanel>
and in the code behind: 并在后面的代码中:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button newButton = new Button { Content = "CreatedBtn" };
newButton.Click += Button_Click;
RelativePanel.SetLeftOf(newButton,sender);
myPanel.Children.Add(newButton);
}
This will work fine, however if you click double times one button, the second new created one will overlap the one created from the first click. 这样可以正常工作,但是如果单击一次按钮,则第二个新创建的按钮将与第一次单击创建的重叠。 If it's not a desired behavior, you will have to do it other way, in that case you need a list of buttons.
如果它不是一个理想的行为,你将不得不以其他方式这样做,在这种情况下你需要一个按钮列表。 I've used horizontal ListView for that:
我使用了水平ListView :
<ListView x:Name="myList">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsStackPanel Orientation="Horizontal" ScrollViewer.HorizontalScrollMode="Enabled" ScrollViewer.VerticalScrollMode="Disabled"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" Click="ListButton_Click"/>
</DataTemplate>
</ListView.ItemTemplate>
<x:String>StartBtn</x:String>
</ListView>
private void ListButton_Click(object sender, RoutedEventArgs e)
{
int index = myList.Items.IndexOf((e.OriginalSource as FrameworkElement).DataContext);
myList.Items.Insert(index, $"Btn {myList.Items.Count}");
}
This need some more styling, but should show the basic idea. 这需要更多的造型,但应该显示基本的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.