ただ Button 以外の、例えば Grid や Canvas などの Command プロパティが存在しないコントロールに Click イベントを登録する場合、どうすれよいか。
UIElement.InputBindings を使うらしい。
MainWindowViewModel という ViewModel クラスがあり、CommandParameter に指定された文字列をメッセージボックスで表示するコマンドが定義されているとする。
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WPFSample.ViewModels"
x:Class="WPFSample.Views.MainWindow"
Height="300"
Width="300"
>
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Canvas Background="Lime"
Margin="10"
>
<Canvas.InputBindings>
<!-- 左クリック -->
<MouseBinding Command="{Binding LeftClickCommand}"
CommandParameter="左クリック"
MouseAction="LeftClick"
/>
<!-- 右クリック -->
<MouseBinding Command="{Binding RightClickCommand}"
CommandParameter="右クリック"
MouseAction="RightClick"
/>
</Canvas.InputBindings>
</Canvas>
</Grid>
</Window>
これでキャンバスを左クリックすれば「左クリック」と書かれたメッセージボックスが表示され、右クリックすれば「右クリック」と書かれたメッセージボックスが表示される。
0 件のコメント:
コメントを投稿