[フレーム]
Last Updated: April 16, 2021
·
35.96K
· mikihiro

WPF ComboBox GotFocus (MVVM)

Prepare

NuGet
- Microsoft.Xaml.Behaviors.Wpf 1.1.31
- ReactiveProperty 7.8.3

Notes

  • Use Behaviors InvokeCommandAction, then set PassEventArgsToCommand="True".
  • You can use ICommand. ReactiveCommand includes ICommand.
  • Determin focus types of ComboBox or ComboBoxItem.
  • .NET5

View

xmlns:bh="http://schemas.microsoft.com/xaml/behaviors"
<ComboBox Width="120" Height="30">
 <bh:Interaction.Triggers>
 <bh:EventTrigger EventName="GotFocus">
 <bh:InvokeCommandAction Command="{Binding ComboBoxFocus}" PassEventArgsToCommand="True" />
 </bh:EventTrigger>
 </bh:Interaction.Triggers>
 <ComboBoxItem>Test Item1</ComboBoxItem>
 <ComboBoxItem>Test Item2</ComboBoxItem>
 <ComboBoxItem>Test Item3</ComboBoxItem>
</ComboBox>

MainManager is model. This code omited model.

ViewModel

public class MainViewModel : INotifyPropertyChanged, IDisposable
{

 private MainManager Model { get; }
 public ReactiveCommand<RoutedEventArgs> ComboBoxFocus { get; } = new();

 public MainViewModel(MainManager model)
 {
 Model = model;
 ComboBoxFocus.Subscribe(e => ComboBox_GotFocus(e)).AddTo(Disposable);
 }

 private void ComboBox_GotFocus(RoutedEventArgs e)
 {
 var type = e.OriginalSource.GetType();
 if (type == typeof(ComboBox))
 {
 Debug.WriteLine("ComboBox Foucus");
 }
 else if (type == typeof(ComboBoxItem))
 {
 Debug.WriteLine("ComboBoxItem Foucus");
 Debug.WriteLine(((ComboBoxItem)e.OriginalSource).Content);
 }
 }

 // INotifyPropertyChanged
 // Dispose

AltStyle によって変換されたページ (->オリジナル) /