问题
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". However, it can't find a way to do that in C# code.
回答1:
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>
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 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.
来源:https://stackoverflow.com/questions/42306705/programmatically-add-buttons-to-a-uwp-app