以编程方式向 UWP 应用添加按钮 [英] 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.
我该怎么做?
我的方法是创建一个 RelativePanel,因为在编辑器中,您可以说将这个放在那个的左边".但是,它找不到在 C# 代码中执行此操作的方法.
My approach was creating a RelativePanel, because in the Editor, you can say "Place this left of that". However, it can't find a way to do that in C# code.
推荐答案
您可以关注 ctron 的评论 并通过在代码中设置附加属性值来完成.示例可能如下所示 - XAML:
You can follow ctron's comment and do it via setting attached property value in the code. The sample can look like this - XAML:
<RelativePanel x:Name="myPanel" Margin="100">
<Button Content="StartBtn" Click="Button_Click"/>
</RelativePanel>
以及后面的代码:
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);
}
这会正常工作,但是如果您单击两次一个按钮,第二个新创建的按钮将与第一次单击创建的按钮重叠.如果这不是所需的行为,您将不得不以其他方式进行,在这种情况下,您需要一个按钮列表.为此,我使用了水平 ListView:
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 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.
这篇关于以编程方式向 UWP 应用添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!