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

时间:2011-03-24 16:29:29

标签: c# wpf mvvm keydown system-tray

我目前正在使用系统托盘图标上下文菜单中的文本框 问题是,文本框对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>  

2 个答案:

答案 0 :(得分:0)

假设“Initial”是ViewModelLocator(Locator)中返回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对我来说很好。如果您按上面的定义命令,希望它可以工作。

答案 1 :(得分: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);