简体   繁体   English

输入@时在文本框中弹出上下文菜单

[英]Pop context menu in textbox when @ is input

I am trying to build a chat application, I would like to mimic facebook tag friends functionality. 我正在尝试构建一个聊天应用程序,我想模仿Facebook标签好友功能。 When the user types @ in the textblock, I want to pop a context menu with a list of items. 当用户在文本块中键入@时,我想弹出一个带有项目列表的上下文菜单。 How can this be triggered in wpf mvvm app? 如何在wpf mvvm应用程序中触发此事件?

Example. 例。 在此处输入图片说明

I would do it the following way : 我将通过以下方式进行操作:

Subscribe to the TextChanged event and whenever there is a change that contains @ then show the popup, otherwise hide it. 订阅TextChanged事件,只要有包含@的更改,就显示弹出窗口,否则将其隐藏。

Note that it tracks for new changes in the TextBox, therefore the popup will disappear as soon as the user presses another key or in your case when the user selected a user from the auto-completion you have provided in the pop-up. 请注意,它跟踪TextBox中的新更改,因此,一旦用户按下另一个键,或者在用户从您从弹出窗口中提供的自动完成中选择用户的情况下,弹出窗口就会消失。

User hasn't typed @ 用户尚未输入@

在此处输入图片说明

User just typed @ 用户刚刚输入@

在此处输入图片说明

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

Code behind: 后面的代码:

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

That said, you might want to further enhance it and integrate it properly your application ;-) 也就是说,您可能想进一步增强它并正确地将其集成到您的应用程序中;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM