MVVMデザインパターンを使用してWPFアプリを作成しており、ユーザーがマウスの中ボタンをクリックしたときにタブが閉じるようにTabItemコントロールを拡張しようとしています。私はInputBindingsを使用してこれを達成しようとしていますが、スタイル内で定義しようとするまでは非常にうまく機能します。DependencyPropertyを使用してスタイルをアタッチしない限り、InputBindingsをスタイルに追加できないことを学びました。だから私はここでこの同様の投稿をたどりました...そしてそれはうまくいきます...ほとんど。マウスの中ボタンを使用して1つのタブを閉じることはできますが、他のタブでは機能しません(すべてのタブは実行時に追加され、同じスタイルを継承します)。
だから私はいくつかの助けが必要です。なぜこれが最初にのみ機能し、その後は機能しないのでしょうか?もちろん、TabItemから継承するカスタムコントロールを作成して機能させることもできますが、プロジェクトでこれが拡張されていることがわかるので、これを理解したいと思います。私はDependencyPropertiesの専門家ではないので、手伝ってください。ありがとう!
スタイル:
<Style TargetType="{x:Type TabItem}">
<Setter Property="w:Attach.InputBindings">
<Setter.Value>
<InputBindingCollection>
<MouseBinding MouseAction="MiddleClick"
Command="{Binding CloseCommand}"/>
</InputBindingCollection>
</Setter.Value>
</Setter>
...
</Style>
クラス
public class Attach
{
public static readonly DependencyProperty InputBindingsProperty =
DependencyProperty.RegisterAttached("InputBindings", typeof(InputBindingCollection), typeof(Attach),
new FrameworkPropertyMetadata(new InputBindingCollection(),
(sender, e) =>
{
var element = sender as UIElement;
if (element == null) return;
element.InputBindings.Clear();
element.InputBindings.AddRange((InputBindingCollection)e.NewValue);
}));
public static InputBindingCollection GetInputBindings(UIElement element)
{
return (InputBindingCollection)element.GetValue(InputBindingsProperty);
}
public static void SetInputBindings(UIElement element, InputBindingCollection inputBindings)
{
element.SetValue(InputBindingsProperty, inputBindings);
}
}