2024/06/09(日)11:02
C#のWPFで簡単なユーザーコントロールを作成するサンプルコード
以下は、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!" というテキストが表示されるユーザーコントロールが表示されます。