599907 ランダム
 HOME | DIARY | PROFILE 【フォローする】 【ログイン】

「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! --/--
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x
2024.03.18
XML
カテゴリ: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



© Rakuten Group, Inc.