WPF click event handler get textblock text

放肆的年华 提交于 2021-01-27 16:13:41

问题


I have a text block in my 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.


回答1:


var tb = sender as TextBox

This results in null because it's actually a TextBlock.

Just change to

var tb = sender as TextBlock



回答2:


Most likely what sender must to be TextBlock. And for the future you should check the sender on the null in order once again not raise an exception:

var tb = sender as TextBlock;

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



回答3:


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);
}



回答4:


Ohh oops didn't see you were trying to cast as TextBox not TextBlock. Assuming you want TextBlock then look at below:

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.



来源:https://stackoverflow.com/questions/23294549/wpf-click-event-handler-get-textblock-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!