WPFでコントロールのプロパティをカスタマイズする方法

WPFでは、既存のコントロールを継承したカスタムコントロールを作成し、カスタムプロパティを追加することで、カスタムコントロールの属性を実現できます。

以下は、MyButton という名前のカスタムコントロールを作成し、MyProperty というカスタムプロパティを追加する方法の簡単な例です。

  1. WPF の新しい UserControl ファイルを作成し、MyButton.xaml という名前を付けます。
  2. MyButton.xaml ファイルを開き、Button コントロールを追加して、その外観と動作を設定します。
<UserControl x:Class="YourNamespace.MyButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Button x:Name="btn" Content="Click Me!" Click="Button_Click"/>
</UserControl>
  1. MyButton.xaml.cs ファイルにて、MyProperty プロパティを定義し、プロパティ変更時に処理を行う。
using System.Windows;
using System.Windows.Controls;

namespace YourNamespace
{
    public partial class MyButton : UserControl
    {
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(string), typeof(MyButton), new PropertyMetadata(""));

        public string MyProperty
        {
            get { return (string)GetValue(MyPropertyProperty); }
            set { SetValue(MyPropertyProperty, value); }
        }

        public MyButton()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 处理按钮点击事件,并使用MyProperty属性
            MessageBox.Show("MyProperty value: " + MyProperty);
        }
    }
}
  1. カスタムコントロールを使用するXAMLファイルにカスタムコントロールを参照し、カスタムプロパティを設定する。
<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YourNamespace"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:MyButton MyProperty="Custom Property Value"/>
    </Grid>
</Window>

カスタムコントロールに属性を追加して、コントロールのカスタマイズや、属性値に応じた処理を実装できます。

bannerAds