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

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

2024.03.13
XML
カテゴリ: C#.NET


以下は、C# WPF の MVVM パターンを使用したサンプルコードです。この例では、MVVM パターンに基づいて、ユーザーが名前を入力してメッセージを表示する機能を持つシンプルなアプリケーションを示しています。


まず、ViewModel を定義します。


```csharp

using System.ComponentModel;

using System.Windows.Input;


namespace MVVMSample

{

    public class MainViewModel : INotifyPropertyChanged

    {

        private string _name;

        private string _message;


        public string Name

        {

            get { return _name; }

            set

            {

                if (_name != value)

                {

                    _name = value;

                    OnPropertyChanged(nameof(Name));

                }

            }

        }


        public string Message

        {

            get { return _message; }

            set

            {

                if (_message != value)

                {

                    _message = value;

                    OnPropertyChanged(nameof(Message));

                }

            }

        }


        public ICommand ShowMessageCommand { get; }


        public MainViewModel()

        {

            ShowMessageCommand = new RelayCommand(ShowMessage);

        }


        private void ShowMessage(object obj)

        {

            Message = $"Hello, {Name}!";

        }


        public event PropertyChangedEventHandler PropertyChanged;


        protected virtual void OnPropertyChanged(string propertyName)

        {

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        }

    }

}

```


次に、RelayCommand を定義します。


```csharp

using System;

using System.Windows.Input;


namespace MVVMSample

{

    public class RelayCommand : ICommand

    {

        private readonly Action<object> _execute;

        private readonly Func<object, bool> _canExecute;


        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)

        {

            _execute = execute ?? throw new ArgumentNullException(nameof(execute));

            _canExecute = canExecute;

        }


        public event EventHandler CanExecuteChanged

        {

            add { CommandManager.RequerySuggested += value; }

            remove { CommandManager.RequerySuggested -= value; }

        }


        public bool CanExecute(object parameter)

        {

            return _canExecute == null || _canExecute(parameter);

        }


        public void Execute(object parameter)

        {

            _execute(parameter);

        }

    }

}

```


最後に、View を定義します。


```xml

<Window x:Class="MVVMSample.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:local="clr-namespace:MVVMSample"

        Title="MVVM Sample" Height="150" Width="300">

    <Grid>

        <StackPanel Margin="10">

            <TextBlock Text="Enter your name:"/>

            <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Margin="0 5"/>

            <Button Content="Show Message" Command="{Binding ShowMessageCommand}" Margin="0 10"/>

            <TextBlock Text="{Binding Message}" Margin="0 10"/>

        </StackPanel>

    </Grid>

</Window>

```


この例では、ViewModel が `INotifyPropertyChanged` インターフェースを実装しており、`RelayCommand` を使用してコマンドを処理します。View では、`TextBox`、`Button`、`TextBlock` をバインディングして、ViewModel のプロパティとコマンドを使用します。


これで、MVVM パターンを使用して簡単な WPF アプリケーションが完成しました。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.03.13 05:29:56


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

© Rakuten Group, Inc.
X
Create a Mobile Website
スマートフォン版を閲覧 | PC版を閲覧
Share by: