2017-12-07 210 views
0

WPFウィンドウでは、デフォルトでカーソルをテキストボックスの1つに配置しようとしています。 は、いくつかの質問と回答を読んだ後、私は次のことを試してみました:wpf MVVMフォーカスカーソルをテキストボックスに移動

XAML:

<StackPanel Grid.Row="1" 
    <StackPanel.Style> 
     <Style> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding UserShouldEditValueNow}" Value="true"> 
        <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=FID}"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </StackPanel.Style> 
    <TextBox Name ="FID" Text="{Binding FixID, UpdateSourceTrigger=PropertyChanged}" 
    FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/> 
</StackPanel> 

CS:(ViewModelに)

this.UserShouldEditValueNow = true; 

私はテキストボックスFID上でカーソルの点滅を確認することが期待しましたウィンドウを開くとき。 ただし、このテキストボックスにはカーソルがありません。 デバッグでは、値をtrueに設定してcsコードを調べていることがわかりました。 なぜですか?

+0

答えのための[この](https://stackoverflow.com/a/1356781/6869276)アプローチを試してみてください。これで、 'FocusExtension'クラスを追加のStackPanelを削除して行く: ' 私のために ' 作品。 – pixela

+0

[ビューモデル(WPF)のテキストボックスにフォーカスを設定(C#)](https://stackoverflow.com/questions/1356045/set-focus-on-textbox-in-wpf-from-view-model-c)の可能な複製) – techvice

答えて

0

解決策:1. FocusExtensionクラスを追加する。 2.フォーカスとKeyboard.FocusはDispatcher.BeginInvokeの内側にあります。

csです。

public static class FocusExtension 
    { 
     public static bool GetIsFocused(DependencyObject obj) 
     { 
      return (bool)obj.GetValue(IsFocusedProperty); 
     } 

     public static void SetIsFocused(DependencyObject obj, bool value) 
     { 
      obj.SetValue(IsFocusedProperty, value); 
     } 

     public static readonly DependencyProperty IsFocusedProperty = 
      DependencyProperty.RegisterAttached(
       "IsFocused", typeof(bool), typeof(FocusExtension), 
       new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)); 

     private static void OnIsFocusedPropertyChanged(
      DependencyObject d, 
      DependencyPropertyChangedEventArgs e) 
     { 
      var uie = (UIElement)d; 
      if ((bool)e.NewValue) 
      { 
       uie.Dispatcher.BeginInvoke(
        new Action(
         delegate{ 
          uie.Focus(); 
          Keyboard.Focus(uie); 
         } 
        ) 
       ); 
      } 
     } 
    } 

の.xaml

 <TextBox Text="{Binding FixID, UpdateSourceTrigger=PropertyChanged}" viewModels:FocusExtension.IsFocused="{Binding UserShouldEditValueNow}" /> 
関連する問題