LoginSignup
3
2

More than 3 years have passed since last update.

KeyTrigger に紐づけたコマンドが何回も発報する

Last updated at Posted at 2021-01-18

困りごと

私のための備忘録。

以下のように 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>
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2