898178 ランダム
 HOME | DIARY | PROFILE 【フォローする】 【ログイン】

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

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

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


以下は、C#のWPFで簡単なユーザーコントロールを作成するサンプルコードです。


まず、新しいユーザーコントロールを作成します。ここでは、"CustomControl.xaml" という名前のXAMLファイルと、"CustomControl.xaml.cs" という名前のコードビハインドファイルを作成します。


CustomControl.xaml:


```xml

<UserControl x:Class="WpfApp.CustomControl"

             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="300" d:DesignWidth="300">

    <Grid>

        <TextBlock Text="This is a custom control!" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="20"/>

    </Grid>

</UserControl>

```


CustomControl.xaml.cs:


```csharp

using System.Windows.Controls;


namespace WpfApp

{

    public partial class CustomControl : UserControl

    {

        public CustomControl()

        {

            InitializeComponent();

        }

    }

}

```


次に、このユーザーコントロールを使用するメインウィンドウを作成します。ここでは、メインウィンドウのXAMLファイルに作成したユーザーコントロールを追加します。


MainWindow.xaml:


```xml

<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:CustomControl HorizontalAlignment="Center" VerticalAlignment="Center"/>

    </Grid>

</Window>

```


これで、簡単なユーザーコントロールが作成されました。メインウィンドウを実行すると、中央に "This is a custom control!" というテキストが表示されるユーザーコントロールが表示されます。






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

Last updated  2024.06.09 11:02:30



© Rakuten Group, Inc.
X