困りごと
私のための備忘録。
以下のように KeyTrigger とコマンドを紐づけたコントロールを用意し、それを TabControl->TabItem に置いてみたところ、掲題のようにコマンドが何回も発報する現象に遭遇。
正確に言うと、タブの選択状態が切り替わるたびに KeyTrigger とコマンドの紐づけが再生成されているようで、切り替えた回数だけコマンドが呼び出されていました。
Region
<UserControl ...略
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:p="http://prismlibrary.com/">
<ComboBox ItemsSource="{Binding XXX, Mode=OneWay}"
Text="{Binding YYY, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
IsReadOnly="{Binding ZZZ, Mode=OneWay}"
IsEditable="True">
<i:Interaction.Triggers>
<i:KeyTrigger ActiveOnFocus="True" Key="Return">
<p:InvokeCommandAction Command="{Binding HogeCommand, Mode=OneTime}"/>
</i:KeyTrigger>
</i:Interaction.Triggers>
</ComboBox>
</UserControl>
Window
<Window ...略
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:p="http://prismlibrary.com/">
<Window.Resources>
<Style x:Key="RegionContent" TargetType="{x:Type ContentControl}">
<Setter Property="p:RegionManager.RegionManager" Value="{Binding RegionManager, RelativeSource={RelativeSource AncestorType={x:Type Window}}, Mode=OneWay}"/>
</Style>
</Window.Resources>
<TabControl>
<TabItem Header="タブ1">
<ContentControl Style="{StaticResource RegionContent}" p:RegionManager.RegionName="Tab1Region"/>
</TabItem>
<TabItem Header="タブ2">
<ContentControl Style="{StaticResource RegionContent}" p:RegionManager.RegionName="Tab2Region"/>
</TabItem>
</TabControl>
</Window>
手がかり
かなり前ですが、同じような現象で困っていた方を発見。
どうやら Blend 時代からの仕様らしく、KeyTrigger を使わずに対応する必要がありそうです。
stack overflow: Blend KeyTrigger fires multiple times
対応策
InputBindings に変えたらこの現象は収まりました。
Region
<UserControl ...略
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:p="http://prismlibrary.com/">
<ComboBox ItemsSource="{Binding XXX, Mode=OneWay}"
Text="{Binding YYY, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
IsReadOnly="{Binding ZZZ, Mode=OneWay}"
IsEditable="True">
<ComboBox.InputBindings>
<KeyBinding Command="{Binding HogeCommand, Mode=OneTime}" Key="Return"/>
</ComboBox.InputBindings>
</ComboBox>
</UserControl>