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

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

2024.06.09
XML
カテゴリ: WPFC#.NET


ユーザーコントロールとして Button をカスタマイズする方法を示します。この例では、カスタムボタンを作成し、外観と機能をカスタマイズします。


まず、カスタムボタン用のユーザーコントロールを作成します。



<!-- CustomButton.xaml -->

<UserControl x:Class="WpfApp.CustomButton"

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

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

    <Button x:Name="button" Content="Custom Button"/>

</UserControl>

```


次に、ユーザーコントロールのコードビハインドで、ボタンの外観や機能をカスタマイズします。


```csharp

// CustomButton.xaml.cs

using System.Windows;

using System.Windows.Controls;


namespace WpfApp

{

    public partial class CustomButton : UserControl

    {

        public CustomButton()

        {

            InitializeComponent();

            button.Click += Button_Click;

        }


        public static readonly DependencyProperty TextProperty =

            DependencyProperty.Register("Text", typeof(string), typeof(CustomButton), new PropertyMetadata("Custom Button"));


        public string Text

        {

            get { return (string)GetValue(TextProperty); }

            set { SetValue(TextProperty, value); }

        }


        private void Button_Click(object sender, RoutedEventArgs e)

        {

            MessageBox.Show("Custom button clicked!");

        }

    }

}

```


このカスタムボタンは、ユーザーコントロールとして Button をラップし、`Text`プロパティを公開してボタンのテキストを設定し、クリックイベントを処理します。


最後に、このカスタムボタンを使用してメインウィンドウで表示します。


```xml

<!-- MainWindow.xaml -->

<Window x:Class="WpfApp.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:WpfApp"

        mc:Ignorable="d"

        Title="MainWindow" Height="450" Width="800">

    <Grid>

        <local:CustomButton Text="Click Me" HorizontalAlignment="Center" VerticalAlignment="Center"/>

    </Grid>

</Window>

```


この例では、`CustomButton` ユーザーコントロールを使用して、メインウィンドウにカスタムボタンを表示しています。ボタンのテキストは `Text` プロパティで設定されます。






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

Last updated  2024.06.09 13:46:49


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

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