WPF学習中「ユーザーコントロール」

紅型 : 古琉球 [1]コンピュータ
出典:国立国会図書館「NDLイメージバンク」 (https://rnavi.ndl.go.jp/imagebank/)
ユーザーコントロールのサンプルです。Viewに配置するコントロールのソースを分割し再利用することができるようです。
スポンサーリンク

プロジェクトの作成

PowerShellで実行。要dotnet.exe

dotnet new wpf -n SimpleUserControl
cd SimpleUserControl
code .

ソースコード

ファイル名:AaaUserControl.xaml

<UserControl x:Class="SimpleUserControl.AaaUserControl"
        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:SimpleUserControl"
        mc:Ignorable="d"
        d:DesignHeight="100" d:DesignWidth="150"
        x:Name="parent">
    <Grid>
        <StackPanel>
            <TextBlock Text="{Binding Property2, ElementName=parent}"></TextBlock>
            <Button Content="ボタン" Width="100" Command="{Binding Command2, ElementName=parent}" />
        </StackPanel>
    </Grid>
</UserControl>

ファイル名:AaaUserControl.xaml.cs

using System;
using System.Windows;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Input;

namespace SimpleUserControl
{
    public partial class AaaUserControl : System.Windows.Controls.UserControl
    {
        public string Property2
        {
            get { return (string)GetValue(Property2Property); }
            set { SetValue(Property2Property, value); }
        }
        public static readonly DependencyProperty Property2Property =
            DependencyProperty.Register(
                "Property2",
                typeof(string),
                typeof(AaaUserControl),
                new PropertyMetadata(string.Empty));
        public ICommand Command2
        {
            get { return (ICommand)GetValue(Command2Property); }
            set { SetValue(Command2Property, value); }
        }
        public static readonly DependencyProperty Command2Property =
            DependencyProperty.Register(
                "Command2",
                typeof(ICommand),
                typeof(AaaUserControl),
                new PropertyMetadata(null));
        public AaaUserControl()
        {
            InitializeComponent();
        }
    }
}

ファイル名:MainWindow.xaml

<Window x:Class="SimpleUserControl.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:SimpleUserControl"
        mc:Ignorable="d"
        x:Name="root"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:AaaUserControl
            Property2="{Binding Property1, ElementName=root}"
            Command2="{Binding Command1, ElementName=root}" />
    </Grid>
</Window>

ファイル名:MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.ComponentModel;

namespace SimpleUserControl
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        protected void OnPropertyChanged(string name) =>  this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

        private string? _property1;
        public string? Property1
        {
            get { return _property1; }
            set { Console.WriteLine("* MainWindow Property1 = {0} ", value); _property1 = value; OnPropertyChanged(nameof(Property1)); }
        }
        class MyCommand : ICommand
        {
            private Action<object?> _action;
            public event EventHandler? CanExecuteChanged;

            public MyCommand(Action<object?> action)
            {
                _action = action;
            }
            public bool CanExecute(object? parameter) => _action != null;                                 
            public void Execute(object? parameter) => _action(parameter);
            public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
        private ICommand? _command1;
        public ICommand? Command1
        {
            get
            {
                return _command1 ?? (_command1 = new MyCommand((o)=>
                    {
                        System.Windows.MessageBox.Show("かきくけこ");
                    }
                ));
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            PropertyChanged += (o, e) => {};
            this.Property1 = "あいうえお";
        }
    }
}

実行

コメント