この種の問題に対する通常の解決策は、適切な(通常は暗黙的な)Style
を使用することです。残念ながら、の形式でInteraction.Behaviors
とInteraction.Triggers
のコレクションを埋め込むことはできません。彼のコメントに@Sinatrによって言及されたthis oneのようないくつかの回避策が存在するが、少なくとも直接的ではない。しかし、よりよい解決策は、さらにあなたは一石二鳥とコマンドに適切なパラメータを渡すことができます添付プロパティと専用のヘルパークラスを作成することである私の意見では
:
public static class NavigationRadioButtonHelper
{
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
name: "Command",
propertyType: typeof(ICommand),
ownerType: typeof(NavigationRadioButtonHelper),
defaultMetadata: new PropertyMetadata(null, HandleCommandChanged));
public static ICommand GetCommand(NavigationRadioButton control)
=> (ICommand)control.GetValue(CommandProperty);
public static void SetCommand(NavigationRadioButton control, ICommand value)
=> control.SetValue(CommandProperty, value);
private static void HandleCommandChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null)
{
((NavigationRadioButton)d).AddHandler(
routedEvent: Mouse.PreviewMouseDownEvent,
handler: (MouseButtonEventHandler)HandlePreviewMouseDown);
}
else
{
((NavigationRadioButton)d).RemoveHandler(
routedEvent: Mouse.PreviewMouseDownEvent,
handler: (MouseButtonEventHandler)HandlePreviewMouseDown);
}
}
private static void HandlePreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var control = (NavigationRadioButton)sender;
var command = GetCommand(control);
var parameter = $"{control.RegionName},{control.ViewName}";
if (command != null && command.CanExecute(parameter))
command.Execute(parameter);
}
}
何ここではコマンドがプロパティに割り当てられたときに、添付されたコマンドを単に実行する関連オブジェクトにハンドラが追加され、必要なパラメータを同時に便利に構築できます。コマンドがnull
に設定されている場合、ハンドラは削除されます。この機能は、単一の添付依存関係プロパティにのみ依存しているので、それは簡単なスタイルと組み合わせて使用することができます、
<Style TargetType="{x:Type vw:NavigationRadioButton}">
<Setter Property="ns:NavigationRadioButtonHelper.Command" Value="{Binding (...)}" />
</Style>
私はあなたがNavigationRadioButton
クラスを変更する力を持っていないと仮定していた場合、このロジックはヘルパークラスを必要とせずにそのクラス内に組み込むことができます。
コレクションは、一般的にのみ割り当てられ、スタイルを経由して取り込むことができません。 2つのプロパティのどちらも公開されておらず、対応するセッターメソッドも公に利用可能ではなく、その値を割り当てることができないという意味で読み取り専用であると見なすことができます。
* "タイプ..."のすべてのコントロールに* "TargetType"のスタイルを追加します。しかしブレンドは一切使用しないでください。 – Sinatr
@Sinatr残念ながら、 'Interaction.Behaviors'と' Interaction.Triggers'コレクションは 'Style'の中では読み込み専用のプロパティであるので使用できません(例えば' Grid.ColumnDefinitions'と同じ問題があります)。 – Grx70
@ Grx70、[doable](https://stackoverflow.com/q/22321966/1997232)。 – Sinatr