簡體   English   中英

C#WPF MVVM - 系統托盤圖標上下文菜單中的文本框

[英]C# WPF MVVM - textbox in system-tray icon contextmenu

我目前正在使用系統托盤圖標的上下文菜單中的文本框。
問題是,文本框對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>  

如果您難以聚焦文本框,那是因為您沒有激活文本框控件所屬的窗口線程。 檢查下面的代碼。 快樂的編碼。

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

假設“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對我來說很好。 如果您按上面的定義命令,希望它可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM