开发者

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"


use the gesture listener for create an event handler like "tap" or double" or whatever.


Use this...

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜