【问题标题】:WPF: Can't figure out focusWPF:无法确定焦点
【发布时间】:2016-02-16 10:34:47
【问题描述】:

WPF 专注让我抓狂:(

在一个全新的测试 WPF 项目中,我有这个窗口...

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <TextBox Grid.Column="0" x:Name="txtStatic" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
        <StackPanel Grid.Column="1" Focusable="False">
            <Border BorderBrush="LightGray" BorderThickness="0 0 1 0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Focusable="False">
                <ContentControl x:Name="con" />
            </Border>
        </StackPanel>
    </Grid>
</Window>

还有这个代码隐藏...

Class MainWindow

    Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        Dim txt As New TextBox
        txt.Name = "txtDynamic"
        Me.con.Content = txt
        txt.Focus()
    End Sub

End Class

两个问题...

  1. 当上面的项目启动并显示主窗口时,为什么我不能开始在运行时创建的文本框(txtDynamic)中输入?看起来它已经有了焦点。

  2. 1234563为什么会这样?

提前致谢。

【问题讨论】:

    标签: wpf vb.net


    【解决方案1】:

    将你的 contentcontrol Focusable 更改为 false

    <ContentControl Focusable="False" x:Name="con" />
    

    在后面的代码中添加,对不起,它是在 C# 中

     var txt = new TextBox();
        txt.Name = "txtDynamic";
        con.Content = txt;
        txt.Focus();
    
       Dispatcher.BeginInvoke(
       DispatcherPriority.ContextIdle,
       new Action(delegate()
       {
           txt.Focus();
       }));
    

    【讨论】:

    • 哇,谢谢...我认为从 WinForms 转到 WPF 会很容易...再想一想;)...再次感谢!!!
    猜你喜欢
    • 2010-11-26
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    相关资源
    最近更新 更多