C# WPF MVVM - 系统托盘图标上下文菜单中的文本框

3

我目前正在尝试在系统托盘图标的上下文菜单中使用文本框。
问题在于,该文本框不响应keydown事件。这意味着我无法向文本框插入文本。


<tb:TaskbarIcon x:Name="NotifyIcon" ToolTip="App" IconSource="/Images/MyIcon.ico" >  
    <tb:TaskbarIcon.ContextMenu>  
        <ContextMenu MaxWidth="180">  
            <MenuItem Width="auto" Header="Template">  
                <MenuItem.HeaderTemplate>  
                    <DataTemplate>  
                        <StackPanel Width="auto" Height="auto" Orientation="Horizontal" >  
                            <TextBox Height="20" Text="{Binding Initial.textBoxText, Source={StaticResource Locator}, Mode=TwoWay}" HorizontalAlignment="Left" 
                                                 Name="txtNumberFromTrail" VerticalAlignment="Center" Width="105" >  
                                <i:Interaction.Triggers>  
                                    <i:EventTrigger EventName="KeyDown">  
                                        <cmd:EventToCommand Command="{Binding Initial.KeyDown, Source={StaticResource Locator}}"
                                                                        PassEventArgsToCommand="True" />  
                                    </i:EventTrigger>  
                                </i:Interaction.Triggers>
                            </TextBox>  
                        </StackPanel>  
                    </DataTemplate>  
                </MenuItem.HeaderTemplate>  
            </MenuItem>  
        </ContextMenu>
    </tb:TaskbarIcon.ContextMenu>  
</tb:TaskbarIcon>  

1
你想记录哪些按键?普通文本按键还是特殊按键(例如箭头键)? - thumbmunkeys
2个回答

0
假设在 ViewModelLocator (Locator) 中 "Initial" 是一个属性,该属性返回 viewmodel 的引用,下面是如何在 viewmodel 中定义命令的代码:
    private RelayCommand<KeyEventArgs> _KeyDown;
    public RelayCommand<KeyEventArgs> KeyDown
    {
        get
        {
            if (_KeyDown == null)
            {
                _KeyDown = new RelayCommand<KeyEventArgs>(delegate(KeyEventArgs e)
                {
                    //Functionality that you need to perform on this event    
                });
            }
            return _KeyDown;
        }
    }

你的XAML看起来很好。如果你按照上面定义命令,希望它能够正常工作。


0
如果你在集中文本框时遇到困难,那是因为你没有激活文本框所属的窗口线程。请检查下面的代码。编码愉快。
[DllImport("USER32.DLL")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);

并且...

tb.ShowCustomBalloon((UIElement)balloon, System.Windows.Controls.Primitives.PopupAnimation.Scroll, null);

HwndSource source = (HwndSource)PresentationSource.FromVisual(balloon);
IntPtr handle = source.Handle;

SetForegroundWindow(handle);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接