WPF TextBox不会失去焦点

时间:2017-07-20 07:57:38

标签: c# wpf textbox focus

我知道还有很多其他人写过这篇文章,但建议的解决方案并没有解决我的问题。

我有一个画廊,当用户自动编辑TextBox中指定的数字时,我需要更新图像。

最初我尝试使用LostFocus事件,但并不总是触发as explained here

如果我将属性绑定为suggested here,如果数字有多个数字,则会有太多事件。

然后我尝试this,但它不起作用。

这就是TextBox定义的方式:

  <TextBox Margin="2" Text="{Binding NImageShown}" FontSize="18" 
           LostFocus="ImageIndex_OnLostFocus"
           Name="ImageIndex" Height="40" Width="60" 
           VerticalAlignment="Center" VerticalContentAlignment="Center" 
           Focusable="True">
  </TextBox>

我通过将窗口附加到MouseDown事件:

来实现第三个解决方案
<Window x:Class="...."
    .....
     MouseDown="Window_MouseDown"....>

 private void Window_MouseDown(object sender, MouseButtonEventArgs e)
 {
      if (ImageIndex.IsFocused)
         Keyboard.ClearFocus();

  }

通过这个解决方案,我发现ImageIndex.IsFocused即使在Keyboard.ClearFocus()之后仍然如此:这就是我认为该解决方案无法解决问题的原因。

任何帮助都非常感谢!

修改 根据建议进行更改:

<Grid Grid.Row="2" Grid.Column="2" Name="GridTextbox">
      <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
       </Grid.ColumnDefinitions>

       .....
       <StackPanel Grid.Column="2" Orientation="Horizontal"
              HorizontalAlignment="Right">
                <TextBox Margin="2" Text="{Binding NImageShown}" FontSize="18" LostFocus="ImageIndex_OnLostFocus"
                         Name="ImageIndex" Height="40" Width="60" VerticalAlignment="Center" VerticalContentAlignment="Center" Focusable="True"></TextBox>
                <Label Style="{DynamicResource LabelStyle}" VerticalAlignment="Center"
                       Content="{Binding NTotalImages}" FontSize="18" Padding="5,0,5,0" Margin="5,5,5,5" />
       </StackPanel>
 </Grid>

 private void Window_MouseDown(object sender, MouseButtonEventArgs e)
 {
     if (ImageIndex.IsFocused)
     {
         GridTextbox.Focus();
         Keyboard.ClearFocus();
     }
 }

即使进行了这些更改,LostFocus也不会触发。

按照这种方式建议更改xaml,并按照以前的说明保留代码:

 <TextBox Margin="2" Text="{Binding NImageShown}" FontSize="18" 
          LostKeyboardFocus="ImageIndex_OnLostFocus" 
          KeyDown="ImageIndex_OnLostFocus"
          Name="ImageIndex" Height="40" Width="60" 
          VerticalAlignment="Center" VerticalContentAlignment="Center" 
          Focusable="True">
  </TextBox>

0 个答案:

没有答案