【问题标题】:XAML How do I access Button that's inside a ListView?XAML 如何访问 ListView 中的按钮?
【发布时间】:2017-10-29 04:08:16
【问题描述】:

我有以下 ListView,它为列表中的每个项目显示一个按钮。我希望按钮在单击时通过其主键“BoxID”并打开一个新页面。由于相应的cs文档无法引用该按钮而出现问题。为什么 cs 函数无法访问此按钮?有没有解决的办法?

XAML:

<ListView x:Name="boxList" ItemsSource="{Binding Boxes}">
    <ListView.ItemTemplate> 
        <DataTemplate> 
            <ViewCell>
                <ViewCell.View>
                    <StackLayout Orientation="Horizontal" Padding="10,0">
                        <StackLayout HorizontalOptions="StartAndExpand">
                            <Button x:Name="editBoxButton" Text="{Binding 
                                    BoxName}" CommandParameter="{Binding 
                                    BoxID}"
                                    FontAttributes="Bold" Clicked="editBox" 
                                    HeightRequest="75" WidthRequest="150" 
                                    FontSize="Medium" BorderColor="Black"/>
                        </StackLayout>
                        <Label HorizontalOptions="EndAndExpand" 
                        VerticalOptions="Center" Text="{Binding Complete}"/>
                    </StackLayout>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

CS:

private void editBox(object sender, EventArgs e) {
    int temp_boxID = editBoxButton.CommandParameter;
    Navigation.PushModalAsync(new EditBoxPage(temp_boxID));
}

谢谢

【问题讨论】:

标签: c# android xaml listview


【解决方案1】:

它无法引用该按钮的原因是它位于DataTemplate 中。

现在你怎么能解决它?很简单,既然事件监听器是按钮的clicked事件,只需将发送者转换为按钮即可。现在您可以通过访问DataContext(如果是UWP)或BindingContext(如果是xamarin)来进一步简化您的工作(因为您也提到了android标签)。您为XAMARIN 修改的代码如下:

 private void editBox(object sender, EventArgs e)
    {

        //if you're using VS2017 with c# 7.0
        if (sender is Button editBoxButton)
        {
            if (editBoxButton.CommandParameter is int temp_boxID)
                Navigation.PushModalAsync(new EditBoxPage(temp_boxID));
        }

        //if not then we'll go the traditional way
        var editBoxButton = sender as Button;
        if(editBoxButton!=null)
        {
            var boxID = editBoxButton.CommandParameter;
            int temp_boxID;
            int.TryParse(boxID.ToString(), out temp_boxID);
            Navigation.PushModalAsync(new EditBoxPage(temp_boxID));

        }
    }

根据您使用的Visual Studio 版本和您使用的语言版本C# 6.0C# 7.0,我提出了两种方法

【讨论】:

    猜你喜欢
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2017-02-09
    • 2016-08-08
    • 2020-01-15
    • 2017-08-15
    相关资源
    最近更新 更多