【问题标题】:WPF click event handler get textblock textWPF单击事件处理程序获取文本块文本
【发布时间】:2014-04-26 01:52:11
【问题描述】:

我的 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>

在后面的代码中,我有一个用于单击(双击)的事件处理程序

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

我收到 NullReferenceException。

【问题讨论】:

  • 你为什么不接受任何答案?

标签: c# wpf event-handling


【解决方案1】:
var tb = sender as TextBox

这导致null,因为它实际上是TextBlock

改成

var tb = sender as TextBlock

【讨论】:

    【解决方案2】:

    sender 很可能是 TextBlock。对于未来,您应该检查 null 上的发件人,以便再次不引发异常:

    var tb = sender as TextBlock;
    
    if (tb != null)
    {
        // doing something here
    }
    

    【讨论】:

      【解决方案3】:

      要使其紧凑和简单,只需进行以下更改:

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

      【讨论】:

        【解决方案4】:

        哦,糟糕,您没有看到您尝试将其转换为 TextBox 而不是 TextBlock。假设你想要 TextBlock 然后看下面:

        我不使用事件背后的代码。我尝试使用命令来做所有事情。但是,我会立即尝试的一种解决方法是在控件上命名并直接在后面的代码中访问它,如下所示:

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

        然后可以在后面访问:

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

        另外请注意,如果 'ClickCount' 是控件 TextBlock 或 TextBox 上的导航属性,我可能是错的。

        【讨论】:

        • 请发表评论,说明为什么 -1 来区分参数。
        猜你喜欢
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 2012-12-18
        • 2015-12-22
        • 1970-01-01
        相关资源
        最近更新 更多