全て
| カテゴリ未分類
| 通常
| 数学
| 投資
| 副業
| 転職・就職
| ブログ
| 株Stock
| VBA
| SharePoint
| REST API
| RenderListDataAsStream
| PowerAutomateDesktop
| Graph API
| PowerApps
| PowerAutomate
| PowerFx
| OfficeScriptオフィススクリプト
| PowerAutomate日時Excel日時相互関係
| PowerShell
| Dataverse
| UiPath
| OneDrive
| LINQ
| VB.NET
| C#.NET
| WPFC#.NET
| Git
カテゴリ:C#.NET
WPFアプリケーションでボタンがクリックされたときに、Windowまたはその他のUI要素をViewModelに渡す必要がある場合、一般的な方法としては、次のようなアプローチがあります。 1. **コマンドパラメータを使用する**: ボタンのクリックに関連付けられたコマンドを使用して、ボタンクリック時に追加情報をViewModelに渡すことができます。一般的には、`ICommand`インターフェースを実装したカスタムコマンドを使用します。コマンドパラメータを使用することで、ボタンのクリック時に任意のオブジェクトをViewModelに渡すことができます。 2. **イベントを介して通知する**: ボタンのクリックイベントをハンドリングし、その際にViewModelに通知を送信することもできます。この場合、ボタンのクリックイベントハンドラー内でViewModelにアクセスし、必要な情報を渡すことができます。 以下に、コマンドパラメータを使用した例を示します。 まず、MainWindow.xamlにボタンとそのコマンドを定義します。 ```xml <Window x:Class="YourNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" xmlns:local="clr-namespace:YourNamespace" Title="MainWindow" Height="450" Width="800"> <Grid> <Button Content="Click me" Command="{Binding ButtonClickCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/> </Grid> </Window> ``` 次に、ViewModelにボタンクリック時のコマンドを実装します。 ```csharp using System.Windows; using System.Windows.Input; namespace YourNamespace { public class MainViewModel { public ICommand ButtonClickCommand { get; } public MainViewModel() { ButtonClickCommand = new RelayCommand<Button>(OnButtonClick); } private void OnButtonClick(Button button) { MessageBox.Show($"Button clicked from {button.Name}"); } } public class RelayCommand<T> : ICommand { private readonly Action<T> _execute; public RelayCommand(Action<T> execute) { _execute = execute; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { _execute((T)parameter); } public event EventHandler CanExecuteChanged; } } ``` このようにすることで、ボタンがクリックされたときに、その親要素であるWindowがViewModelに渡されます。その後、ViewModelでそのWindowを使用して任意の処理を実行することができます。 お気に入りの記事を「いいね!」で応援しよう
Last updated
2024.03.18 07:37:57
[C#.NET] カテゴリの最新記事
|