Programmatically add buttons to a UWP app

◇◆丶佛笑我妖孽 提交于 2019-12-11 04:47:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!