【问题标题】:C# WPF MVVM - textbox in system-tray icon contextmenuC# WPF MVVM - 系统托盘图标上下文菜单中的文本框
【发布时间】:2011-03-24 16:29:29
【问题描述】:

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

【问题讨论】:

  • 您要记录哪些键?普通文本键或特殊键(例如箭头键)?

标签: c# wpf mvvm keydown system-tray


【解决方案1】:

假设“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 对我来说似乎很好。如果您如上所述定义命令,希望它会起作用。

【讨论】:

    【解决方案2】:

    如果您难以聚焦文本框,那是因为您没有激活文本框控件所属的窗口线程。检查下面的代码。编码愉快。

    [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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多