简体   繁体   English

另一个“名称'itembutton'在当前上下文中不存在”(WP8,XAML)

[英]Another “The name 'itembutton' does not exist in the current context” (WP8, XAML)

I know that this question has been posted about a thousand times, but I did not find a solution that solved my problem. 我知道这个问题已经发布了大约一千次,但是我没有找到解决我的问题的解决方案。

I've got a LongListSelector with this ItemTemplate : 我有一个LongListSelector与此ItemTemplate

<DataTemplate x:Key="AddrBookItemTemplate">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <TextBlock FontWeight="Bold" Text="{Binding Name}" HorizontalAlignment="Stretch" VerticalAlignment="Center"  Grid.Column="0" Grid.Row="0" />
    <Button x:Name="itembutton" CommandParameter="{Binding ItemID}" Content="{Binding ButtonCaption}" Width="150" HorizontalAlignment="Right" Grid.Column="1" Grid.Row="0" Click="ItemButtonClick"/>
  </Grid>
</DataTemplate>

So what happens is simply that I get this beautiful error message that I posted in the title. 因此,发生的事情仅仅是我收到了标题中发布的漂亮错误消息。 And I do not have a clue, why?! 而且我不知道,为什么?!

private void ItemButtonClick(object sender, RoutedEventArgs e)
{
  if (sender == this.itemButton) {
    ....

From the DataTemplate it looks like you're showing this button in a container like a ListBox or LongListSelector . DataTemplate看来,您正在像ListBoxLongListSelector这样的容器中显示此按钮。

That means that there isn't an itembutton in this scope (presumably this is either UserControl or PhoneApplicationPage ): there is in fact one for each of your ListBoxItems ! 这意味着,没有一个itembuttonthis范围内(想必this是无论UserControlPhoneApplicationPage ):其实也有一个为每个的ListBoxItems

You'll have to find another way of finding your button. 您必须找到另一种找到按钮的方式。

Update : You should find that the DataContext of your button matches the item of the list it is contained in. That's probably the easiest way of proceeding: however if all else fails you can use the Tag property as you suggest. 更新 :您应该发现按钮的DataContext与包含在其中的列表项匹配。这可能是最简单的处理方法:但是,如果其他所有操作失败,则可以按照您的建议使用Tag属性。

Like: 喜欢:

private void ItemButtonClick(object sender, RoutedEventArgs e)
{
    var theButton = (Button) sender;
    var myItem = (TypeOfAnObjectInMyList) theButton.DataContext;
    doSomethingWithMyItem(myItem);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM