简体   繁体   中英

How click a TextBlock in DataTemplate?

This is my XAML code:

<ListBox ItemsSource="{Binding}" Name="listBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <StackPanel Width="370">
                    <TextBlock Text="{Binding AuthorName}"  x:Name="author" MouseEventLeftDown="click"/>
                </StackPanel>
            </StackPanel>                       
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And the Click Handler

private void click(object sender, RoutedEventArgs e)
{
    if(author.Text.Equals("Hi"))
    {
       // Do Something Special
    }
} 

The error is:

Error: The name 'author' does not exist in the current context

But I don't understand what is causing this error or why it is occurring.

Your TextBlock with the Name author doesn't exist in the scope of your click handler because it's in a DataTemplate . What's happening is that the author TextBlock is created once for every one of your data items (Presumably an Author class or a Book class of some kind), so you literally can have dozens of controls named author .

You are better off casting your sender in your click handler to a text box and then checking its text property. Something like this:

private void click(object sender, RoutedEventArgs args)
{
  var textBox = sender as TextBox;
  if(textBox == null)
     return;

  if(textBox.Text.Equals("hi"))
  {
     // Do Something Crazy!
  }
}

It's probably better to use a UI element designed for touch, such as a HyperlinkButton or a Button. You can style these any way you would like to - especially if you use Expression Blend - but it is good design to include some visual feedback about the Touch.

Also - I'm not sure about your == code - you're comparing the sender (a UI element) against some string expression?

First off, your TextBlock is defined in a DataTemplate; try x:Name instead of Name on your TextBlock.

Secondly it might be quite tricky to click your TextBlock since you will have to press an exact pixel in your TextBlock. To make it easier to click your TextBlock you might want to put a Background on your TextBlock , so it will be a lot easier to click. You can even make the background transparent:

Background="Transparent"

使用手势侦听器创建事件处理程序,例如“ tap”或“ double”等。

Use this...

private void click(object sender, RoutedEventArgs e)
    {
        var author = (TextBlock)sender;

        if (author.Text.Equals("Hi"))
        {
            // Do Something Special    
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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