WPF 单击事件处理程序获取文本块文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23294549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF click event handler get textblock text
提问by Yogevnn
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。
回答by Jon B
var tb = sender as TextBox
This results in nullbecause it's actually a TextBlock.
这导致null因为它实际上是一个TextBlock.
Just change to
只需更改为
var tb = sender as TextBlock
回答by Anatoliy Nikolaev
Most likely what sendermust to be TextBlock. And for the future you should check the sender on the nullin order once again not raise an exception:
很可能sender必须是什么TextBlock。对于将来,您应该检查发件人null,以便再次不会引发异常:
var tb = sender as TextBlock;
if (tb != null)
{
// doing something here
}
回答by TheGaMeR123
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);
}
回答by TMan
Ohh oops didn't see you were trying to cast as TextBox not TextBlock. Assuming you want TextBlock then look at below:
Ohh oops 没有看到您试图将其转换为 TextBox 而不是 TextBlock。假设你想要 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 上的导航属性,我可能是错误的但 idk。

