【WPF】任意のイベントでコマンド実行する
任意のイベントで任意のコマンド実行する方法。
▽▼ソースコード▼▽
■MainWindow.xaml
(以下が必要)
・xmlns:prism="http://prismlibrary.com/"
・xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
EventNameに"Loaded"とすれば画面読み込み時にコマンド(MouseLeftButtonDownCmd)を実行する。
※EventNameはインテリセンスが効かないので調べて使おう
<Window x:Class="MyWorkProject.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding Title}" Height="350" Width="525"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <prism:InvokeCommandAction Command="{Binding MouseLeftButtonDownCmd}"/> </i:EventTrigger> </i:Interaction.Triggers> <Grid> <StackPanel> <ContentControl prism:RegionManager.RegionName="ContentRegion" /> </StackPanel> </Grid> </Window>
■MainWindowViewModel.cs
using MyWorkProject.Views; using Prism.Commands; using Prism.Mvvm; using Prism.Regions; namespace MyWorkProject.ViewModels { public class MainWindowViewModel : BindableBase { private IRegionManager _regionManager; private string _title = "Prism Application"; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } public DelegateCommand MouseLeftButtonDownCmd { get; } public MainWindowViewModel(IRegionManager regionManager) { _regionManager = regionManager; MouseLeftButtonDownCmd = new DelegateCommand(ShowWorkA); } public void ShowWorkA() { _regionManager.RequestNavigate("ContentRegion", nameof(WorkA)); } } }
■WorkA.xaml
<UserControl x:Class="MyWorkProject.Views.WorkA" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True"> <Grid> <StackPanel> <TextBlock Text="WorkA" FontSize="20" FontWeight="Bold"/> </StackPanel> </Grid> </UserControl>
■WorkAViewModel.cs
using Prism.Mvvm; namespace MyWorkProject.ViewModels { public class WorkAViewModel : BindableBase { public WorkAViewModel() { } } }