Xamarin 表单。如何在应用程序运行时更改元素

问题描述 投票:0回答:1

我要求一个看似相当简单的事情来改变元素,但我似乎做不到。我的应用程序有一个简单的轮播视图布局,每个页面上都有一个按钮。单击按钮时,按钮上的文本应该发生变化。我尝试使用下面相当简单的方法:

void ChangeButton(object sender, EventArgs e)
{
    var button = sender as Button;
    button.Text = "some text";
}

它的工作方式尽可能奇怪。当您单击某个按钮时,文本会发生变化,但它不是在一个按钮上发生变化,而是在多个按钮上发生变化。也许布局本身工作正常,但我是否遗漏了一些东西?不管怎样,我想知道有哪些工作选择?

我还尝试在单击按钮时更改轮播视图源。嗯,那也没用。

这是xaml代码:

<ContentPage.Content>
    <StackLayout>
        <CarouselView x:Name="PlayersCarouselView">
            <CarouselView.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Button Text="{Binding Text}" Clicked="ChangeButton"/>
                    </StackLayout>
                </DataTemplate>
            </CarouselView.ItemTemplate>
        </CarouselView>
    </StackLayout>
</ContentPage.Content>

这是 C# 代码:

public ButtonList()
    {
        InitializeComponent();
        PlayersCarouselView.Loop = false;

        List<Button> buttons = new List<Button>() { 
            new Button { Text= "1"},
            new Button { Text = "2"},
            new Button { Text= "3"},
            new Button { Text = "4"},
            new Button { Text= "5"},
            new Button { Text = "6"},
            new Button { Text = "7"},
            new Button { Text= "8"},
            new Button { Text = "9."},
            new Button { Text= "10"},
            new Button { Text = "11"},
            new Button { Text= "12"},
            new Button { Text = "13"},
            new Button { Text= "14"},
            new Button { Text = "15"},
            new Button { Text = "16"},
            new Button { Text= "17"},
            new Button { Text = "18."}
        };

        PlayersCarouselView.ItemsSource = buttons;  
    }
c# xamarin xamarin.forms xamarin.android
1个回答
0
投票

解决方案非常糟糕,但我决定使用 CarouselPage 而不是 CarouselView。我还没有完成所有测试,但它似乎有效。至少按钮文本会发生应有的变化。

© www.soinside.com 2019 - 2024. All rights reserved.