【问题标题】:How to focusing the cursor on textbox in wpf with xaml code?如何使用 xaml 代码将光标聚焦在 wpf 中的文本框上?
【发布时间】:2023-03-29 18:17:01
【问题描述】:
<Grid x:Name="LayoutRoot">
    <Button x:Name="btn_A" Content="A" HorizontalAlignment="Left" Height="36" Margin="194,160,0,0" VerticalAlignment="Top" Width="70" Click="Button_Click" />
    <TextBox  x:Name="txt_focus"  HorizontalAlignment="Left" Height="34.5" Margin="177,98,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="97" TextChanged="TextBox_TextChanged" />
</Grid>

c#代码如下

public partial class focus : Window
{
    public focus()
    {
        this.InitializeComponent();         
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {           
        txt_focus.Focus();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {          

        txt_focus.Text += btn_A.Content.ToString();
    }

    private void txt_focus_GotFocus(object sender, RoutedEventArgs e)
    {
        int count = txt_focus.Text.Length;
        txt_focus.CaretIndex = count;
    }
}

上面的代码运行良好。但我需要的是,我必须在 xaml 中实现以下代码

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{           
    txt_focus.Focus();
}

【问题讨论】:

  • 什么是“聚焦光标文本框”?
  • 你是什么意思,@Chandru A?

标签: c# wpf xaml


【解决方案1】:

你可以试试这段代码

<StackPanel Orientation="Vertical"
            FocusManager.FocusedElement="{Binding ElementName=txt_focus}">
    <TextBox x:Name="txt_focus" 
             HorizontalAlignment="Left"
             Height="34.5"
             Margin="167.5,139,0,0"
             TextWrapping="Wrap"
             VerticalAlignment="Top"
             Width="97"
             TextChanged="TextBox_TextChanged" />
</StackPanel>

【讨论】:

  • 不使用 StackPanel。我该怎么办?
【解决方案2】:

您可以使用 javascript 并在此处使用此代码:

if(isset($_REQUEST['sub_con_page'])) 
{ 
//correct 
} 
else  
{ ?> 
<script type="text/javascript"> 
$(document).ready(function() { 
  $("#txt_focus").focus(); 
}); 
</script> 
<?php } ?> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 2011-02-21
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多