简体   繁体   English

WPF单击事件处理程序获取文本块文本

[英]WPF click event handler get textblock text

I have a text block in my xaml: 我的xaml中有一个文本块:

<DataTemplate x:Key="InterfacesDataTemplate"
              DataType="ca:Interface">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="1" Text="{Binding Path=Name}" 
                   MouseLeftButtonDown="interface_mouseDown"/>
    </Grid>
</DataTemplate>

On the code behind I have an event handler for click (double-click) 在后面的代码我有一个事件处理程序单击(双击)

private void interface_mouseDown(object sender, MouseButtonEventArgs e)
{
    var tb = sender as TextBox;
    if (e.ClickCount == 2)
        MessageBox.Show("Yeah interfac " + tb.Text);
}

I'm getting a NullReferenceException. 我得到一个NullReferenceException。

var tb = sender as TextBox

This results in null because it's actually a TextBlock . 这导致null因为它实际上是一个TextBlock

Just change to 只需改为

var tb = sender as TextBlock

Most likely what sender must to be TextBlock . 最有可能的是sender必须是TextBlock And for the future you should check the sender on the null in order once again not raise an exception: 并且对于将来,您应该检查null上的发件人,以便再次不引发异常:

var tb = sender as TextBlock;

if (tb != null)
{
    // doing something here
}

To make it compact and easy just do these changings: 为了使它紧凑和简单,只需做这些改变:

private void interface_mouseDown(object sender, MouseButtonEventArgs e)
{
   if (e.ClickCount == 2)
    MessageBox.Show("Yeah interfac " + ((TextBlock)sender).Text);
}

Ohh oops didn't see you were trying to cast as TextBox not TextBlock. 哦oops没有看到你试图扮演TextBox而不是TextBlock。 Assuming you want TextBlock then look at below: 假设您想要TextBlock,请查看以下内容:

I don't use code behind events. 我不使用事件背后的代码。 I try to use commands to do everything. 我尝试使用命令来做所有事情。 However, one workaround I would immediately try is putting a name on the control and accessing it directly in code behind like so: 但是,我会立即尝试的一个解决方法是在控件上添加一个名称并直接在代码后面访问它,如下所示:

    <TextBlock Grid.Column="1" x:Name="MyTextBlock"
           Text="{Binding Path=Name}" MouseLeftButtonDown="interface_mouseDown"/>
        </Grid>
    </DataTemplate>

Then can access in back: 然后可以在后面访问:

  private void interface_mouseDown(object sender, MouseButtonEventArgs e)
  {
    if (MyTextBlock.ClickCount == 2)
        MessageBox.Show("Yeah interfac " + MyTextBlock.Text);
  }

Also note, i could be wrong but idk if 'ClickCount' is a nav property on the control TextBlock or TextBox. 还要注意,如果'ClickCount'是控件TextBlock或TextBox上的nav属性,我可能错了但是idk。

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

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