小编shr*_*sha的帖子

wpf 使用 xaml 将键盘焦点设置在文本框上

在窗口加载后的 wpf 项目中,我试图使用 xaml 将焦点设置在文本框上。

我的文本框在网格内。这是我使用的代码

<Grid Name="gvLoginPage"
      Margin="0,30,0,0"
      FocusManager.FocusedElement="{Binding ElementName=txtUserName}">
 <TextBox Name="txtUserName"
          Focusable="True"
          ToolTip="Please enter your user name"
          Width="300"
          Height="22"
          VerticalContentAlignment="Top"
          TextWrapping="Wrap"
          Grid.Row="0"
          Grid.Column="1"
          BorderBrush="Black">
<Grid>
Run Code Online (Sandbox Code Playgroud)

此代码正在设置焦点,但光标没有闪烁,我无法输入任何内容。

然后我遇到了这个问题获取和恢复 WPF 键盘焦点,他解释说有两种类型的焦点,一种是逻辑焦点,另一种是键盘焦点,FocusManager.FocusedElement 设置逻辑焦点而不是键盘焦点。所以我无法获得闪烁的光标。

使用后面的代码我可以解决这个问题

Keyboard.Focus(txtUserName);
Run Code Online (Sandbox Code Playgroud)

但我想尽可能少地保留我的代码。所以请有人帮助我使用 xaml 将键盘焦点设置在文本框上。

wpf xaml

4
推荐指数
1
解决办法
7412
查看次数

如何停止和恢复worker服务?

在 WPF 应用程序中,我配置了一个托管服务来在后台执行特定活动(参见本文)。这是在 App.xaml.cs 中配置托管服务的方式。

public App()
        {
            var environmentName = Environment.GetEnvironmentVariable("HEALTHBOOSTER_ENVIRONMENT") ?? "Development";
            IConfigurationRoot configuration = SetupConfiguration(environmentName);
            ConfigureLogger(configuration);
            _host = Host.CreateDefaultBuilder()
                .UseSerilog()
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>()
                    .AddOptions()
                    .AddSingleton<IMailSender, MailSender>()
                    .AddSingleton<ITimeTracker, TimeTracker>()
                    .AddSingleton<NotificationViewModel, NotificationViewModel>()
                    .AddTransient<NotificationWindow, NotificationWindow>()
                    .Configure<AppSettings>(configuration.GetSection("AppSettings"));
                }).Build();

            AssemblyLoadContext.Default.Unloading += Default_Unloading;

            Console.CancelKeyPress += Console_CancelKeyPress;

            SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
        }
Run Code Online (Sandbox Code Playgroud)

并开始启动

/// <summary>
    /// Handles statup event
    /// </summary>
    /// <param name="e"></param>
    protected override async void OnStartup(StartupEventArgs e)
    {
        try
        {
            Log.Debug("Starting the application");
            await _host.StartAsync(_cancellationTokenSource.Token);
            base.OnStartup(e);
        }
        catch …
Run Code Online (Sandbox Code Playgroud)

c# wpf task .net-core ihostedservice

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

wpf ×2

.net-core ×1

c# ×1

ihostedservice ×1

task ×1

xaml ×1