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

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

2024.06.09
XML
カテゴリ: WPFC#.NET


C# WPFでコンバーターリソース(ValueConverter)を活用するサンプルコードを紹介します。この例では、ブール値を文字列に変換するシンプルなコンバーターを作成し、ボタンの背景色を変更するために使用します。


### 1. プロジェクトのセットアップ



2. プロジェクト名を「ConverterSample」とします。


### 2. コンバーターの作成


プロジェクト内に新しいクラス「BoolToColorConverter.cs」を作成します。


```csharp

using System;

using System.Globalization;

using System.Windows.Data;

using System.Windows.Media;


namespace ConverterSample

{

    public class BoolToColorConverter : IValueConverter

    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

        {

            if (value is bool booleanValue)

            {

                return booleanValue ? Brushes.Green : Brushes.Red;

            }

            return Brushes.Transparent;

        }


        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

        {

            throw new NotImplementedException();

        }

    }

}

```


### 3. ViewModelの作成


「MainWindow.xaml.cs」に対応するViewModelを作成します。「MainViewModel.cs」を「ViewModels」ディレクトリに追加します。


```csharp

using System.ComponentModel;

using System.Runtime.CompilerServices;


namespace ConverterSample.ViewModels

{

    public class MainViewModel : INotifyPropertyChanged

    {

        private bool _isButtonClicked;


        public bool IsButtonClicked

        {

            get { return _isButtonClicked; }

            set

            {

                _isButtonClicked = value;

                OnPropertyChanged();

            }

        }


        public event PropertyChangedEventHandler PropertyChanged;


        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)

        {

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

        }

    }

}

```


### 4. Viewの作成


「MainWindow.xaml」を以下のように修正します。


```xml

<Window x:Class="ConverterSample.MainWindow"

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

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

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:local="clr-namespace:ConverterSample"

        xmlns:vm="clr-namespace:ConverterSample.ViewModels"

        mc:Ignorable="d"

        Title="MainWindow" Height="200" Width="400">

    <Window.Resources>

        <local:BoolToColorConverter x:Key="BoolToColorConverter" />

    </Window.Resources>

    <Window.DataContext>

        <vm:MainViewModel />

    </Window.DataContext>

    <Grid>

        <StackPanel>

            <Button Content="Click Me" 

                    Command="{Binding ChangeColorCommand}"

                    Background="{Binding IsButtonClicked, Converter={StaticResource BoolToColorConverter}}"

                    Margin="10"/>

            <TextBlock Text="{Binding IsButtonClicked, StringFormat='Button Clicked: {0}'}" Margin="10"/>

        </StackPanel>

    </Grid>

</Window>

```


### 5. ViewModelにCommandを追加


「MainViewModel.cs」にCommandを追加します。


```csharp

using System.ComponentModel;

using System.Runtime.CompilerServices;

using System.Windows.Input;


namespace ConverterSample.ViewModels

{

    public class MainViewModel : INotifyPropertyChanged

    {

        private bool _isButtonClicked;


        public bool IsButtonClicked

        {

            get { return _isButtonClicked; }

            set

            {

                _isButtonClicked = value;

                OnPropertyChanged();

            }

        }


        public ICommand ChangeColorCommand { get; }


        public MainViewModel()

        {

            ChangeColorCommand = new RelayCommand(ChangeColor);

        }


        private void ChangeColor(object parameter)

        {

            IsButtonClicked = !IsButtonClicked;

        }


        public event PropertyChangedEventHandler PropertyChanged;


        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)

        {

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

        }

    }


    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;

            _canExecute = canExecute;

        }


        public bool CanExecute(object parameter)

        {

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

        }


        public void Execute(object parameter)

        {

            _execute(parameter);

        }


        public event EventHandler CanExecuteChanged

        {

            add { CommandManager.RequerySuggested += value; }

            remove { CommandManager.RequerySuggested -= value; }

        }

    }

}

```


### 6. アプリケーションの実行


以上のコードを実行すると、「Click Me」ボタンをクリックするたびにボタンの背景色が緑と赤に交互に変わります。また、テキストブロックにはボタンがクリックされた状態が表示されます。


### まとめ


このサンプルでは、コンバーターリソースを使ってブール値を色に変換し、ボタンの背景色を変更しました。コンバーターを使用することで、UI要素の見た目や動作を簡単に変更できるようになります。MVVMパターンと組み合わせることで、コードの分離と再利用性が向上し、テストしやすいコードを書くことができます。






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

Last updated  2024.06.09 07:10:20


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

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