2017-10-29 89 views
0

我有以下ListView显示列表中每个项目的按钮。我想让按钮在点击时通过主键'BoxID'并打开一个新页面。问题出现是由于相应的cs文档无法引用按钮。为什么cs功能无法访问此按钮?有没有解决的办法?XAML如何访问ListView中的Button?

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)); 
} 

感谢

+0

检查出来https://stackoverflow.com/questions/25912091/how-do-i-pass-the-button-as-commandparameter-from-xaml-in-a-xamarin-forms-page –

回答

1

它之所以不能够引用到该按钮是因为它是在一个DataTemplate

现在你怎么解决它?这很简单,因为事件监听器是按钮的clicked事件,只需将发件人作为按钮投下。现在,您可以通过访问DataContext来简化工作,如果它是UWPBindingContext如果它是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