2013-10-09 71 views
0

我正在嘗試構建聊天應用程序,我想模仿Facebook標記朋友的功能。當用戶在文本塊中鍵入@時,我想彈出一個包含項目列表的上下文菜單。這在wpf mvvm應用程序中如何觸發?在輸入@時在文本框中彈出上下文菜單

例子。 enter image description here

+0

文本框或文本塊,如果它是一個文本塊你是如何在數據進入,在文本框的疊加? – Sorceri

回答

1

我會做下列方式:

訂閱TextChanged事件,每當有一個包含@然後顯示彈出菜單的改變,否則隱藏它。

請注意,它會跟蹤文本框中的新更改,因此彈出窗口將在用戶按下另一個鍵時消失,或者在用戶從彈出窗口中提供的自動完成中選擇用戶的情況下,向上。

用戶未輸入@剛鍵入@

enter image description here

<Window x:Class="WpfApplication11.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Popup x:Name="MyPopup" Placement="Center"> 
      <Popup.Child> 
       <Border BorderBrush="Red" BorderThickness="1" Background="White"> 
        <Grid> 
         <TextBlock>My popup</TextBlock> 
        </Grid> 
       </Border> 
      </Popup.Child> 
     </Popup> 
     <TextBox TextChanged="TextBoxBase_OnTextChanged" /> 
    </Grid> 
</Window> 

代碼背後

enter image description here

用戶:

using System.Windows; 
using System.Windows.Controls; 

namespace WpfApplication11 
{ 
    /// <summary> 
    ///  Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e) 
     { 
      var textBox = (TextBox) sender; 
      foreach (TextChange textChange in e.Changes) 
      { 
       string substring = textBox.Text.Substring(textChange.Offset, textChange.AddedLength); 
       if (substring == "@") 
       { 
        MyPopup.IsOpen = true; 
       } 
       else 
       { 
        MyPopup.IsOpen = false; 
       } 
      } 
     } 
    } 
} 

這就是說,你可能想要進一步提升,並妥善整合其應用程序;-)

+0

這會讓我開始,感謝分享這個解決方案。 –