簡體   English   中英

WPF單擊事件處理程序獲取文本塊文本

[英]WPF click event handler get textblock text

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

var tb = sender as TextBox

這導致null因為它實際上是一個TextBlock

只需改為

var tb = sender as TextBlock

最有可能的是sender必須是TextBlock 並且對於將來,您應該檢查null上的發件人,以便再次不引發異常:

var tb = sender as TextBlock;

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

為了使它緊湊和簡單,只需做這些改變:

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

哦oops沒有看到你試圖扮演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上的nav屬性,我可能錯了但是idk。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM