WPF のユーザー コントロールとカスタム コントロール

WPF のユーザー コントロールとカスタム コントロール

WPF と WinForm のどちらにも、ユーザー コントロール (UserControl) とカスタム コントロール (CustomControl) があり、これら 2 つのコントロールは、機能の再利用を実現するために既存のコントロールをカプセル化したものです。この記事では、これら 2 つのコントロールについて説明します。

  1. ユーザーコントロール
    • 複合コントロールの使用に注意してください。つまり、複数の既存のコントロールが再利用可能なコントロール グループを形成します。
    • XAML とバックグラウンド コードで構成され、緊密にバインドされています
    • テンプレートの書き換えはサポートされていません
    • ユーザーコントロールから継承
  2. カスタムコントロール
    • 既存のコントロールを継承して機能拡張したり、新たな機能を追加したりするなど、コントロールを完全に自分で実装する
    • バックグラウンドコードとGeneric.xamlの組み合わせ
    • 使用時のテンプレートの書き換えをサポート
    • コントロールから継承

ユーザーコントロール

RelativeSourceユーザー コントロールは、一般的な WPF フォームに似ており、比較的理解しやすいですが、内部でバインドを使用する場合は、適切なカプセル化を実現する方法でバインドする必要があることに注意してください。単純なケース:

  • ユーザーコントロールを定義する
<UserControl
    x:Class="WpfApp19.UserControl1"
    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:local="clr-namespace:WpfApp19"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">
    <Grid>
        <!--下面绑定都要用RelativeSource作为源-->
        <StackPanel>
            <TextBox
                Width="100"
                BorderThickness="2"
                Text="{Binding value, RelativeSource={RelativeSource AncestorType=UserControl}}" />
            <Button
                Width="100"
                Command="{Binding Command, RelativeSource={RelativeSource AncestorType=UserControl}}"
                Content="Ok" />
        </StackPanel>
    </Grid>
</UserControl>

コードビハインド

//根据需要定义依赖属性 
//所需要绑定的值
 public int value
 {
    
    
     get {
    
     return (int)GetValue(valueProperty); }
     set {
    
     SetValue(valueProperty, value); }
 }
 public static readonly DependencyProperty valueProperty =
     DependencyProperty.Register("value", typeof(int), typeof(UserControl1), new PropertyMetadata(0));

 //所需要绑定的命令
 public ICommand Command
 {
    
    
     get {
    
     return (ICommand)GetValue(CommandProperty); }
     set {
    
     SetValue(CommandProperty, value); }
 }
 public static readonly DependencyProperty CommandProperty =
     DependencyProperty.Register("Command", typeof(ICommand), typeof(UserControl1), new PropertyMetadata(default(ICommand)));


 //所需要绑定的命令参数
 public object CommandParemeter
 {
    
    
     get {
    
     return (object)GetValue(CommandParemeterProperty); }
     set {
    
     SetValue(CommandParemeterProperty, value); }
 }
 public static readonly DependencyProperty CommandParemeterProperty =
     DependencyProperty.Register("CommandParemeter", typeof(object), typeof(UserControl1), new PropertyMetadata(0));
  • ユーザーコントロールを使用する
<Window x:Class="WpfApp19.MainWindow"
        ...
        xmlns:local="clr-namespace:WpfApp19"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:UserControl1 value="{Binding }" Command="{Binding }"/>
    </Grid>
</Window>

カスタムコントロール

CustomControl1.csクリックしてカスタム コントロールを追加すると、ファイルとディレクトリが追加され、Themesディレクトリの下にGeneric.xamlファイルが存在します。これがカスタム コントロールのスタイルです。编辑模板特定のコントロール操作に対してよく生成されるスタイルは、実際にはで定義されたスタイル创建副本です。Generic.xamlさらに、同じソフトウェアが異なる Windows バージョンで実行されると、パフォーマンスが異なったり、異なるシステムではデフォルトのテーマと異なり、一部のシステムが実行できない場合があります。実際、wpf コントロールがカスタム スタイルを見つけられない場合、システムからスタイルを取得します。検索順序は、最初に、それが配置されているアセンブリを見つけることです。アセンブリがフィーチャーを定義している場合は、属性値がチェックされます。属性が Yes の場合、特定のテーマ リソースがThemeInfo存在ThemeInfoDictionaryLocationNoneないことを意味し、値はSourceAssembly特定のリソースがアセンブリの内部に定義されていることを意味し、値はアセンブリの外部にあることを意味します。それでも見つからない場合、プログラムは取得します。それExternalAssembly自体は、実際にはシステムのデフォルトのスタイルに関連しています。themes/generic.xamlgeneric.xaml

さまざまな xaml に対応するシステム テーマ

画像-20230208144759832

ボタンケース

画像

C#ファイル

public class Switch : ToggleButton
{
    
    
    static Switch()
    {
    
    
        //通过重写Metadata,控件就会通过程序集themes文件夹下的generic.xaml来寻找系统默认样式
        DefaultStyleKeyProperty.OverrideMetadata(typeof(Switch), new FrameworkPropertyMetadata(typeof(Switch)));
    }
}

Themes フォルダー内の Generic.xaml ファイル

このファイルには中国語を含めることはできず、コメントも含めることはできないことに注意してください。

<Style TargetType="{x:Type local:Switch}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:Switch}">
                <Grid>
                    <Border
                        Name="dropdown"
                        Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
                        Margin="-23"
                        CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
                        Visibility="Collapsed">
                        <Border.Background>
                            <RadialGradientBrush>
                                <GradientStop Offset="1" Color="Transparent" />
                                <GradientStop Offset="0.7" Color="#5500D787" />
                                <GradientStop Offset="0.59" Color="Transparent" />
                            </RadialGradientBrush>
                        </Border.Background>
                    </Border>
                    <Border
                        Name="bor"
                        Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
                        Background="Gray"
                        BorderBrush="DarkGreen"
                        BorderThickness="5"
                        CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}">
                        <Border
                            Name="bor1"
                            Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
                            Margin="2"
                            Background="#FF00C88C"
                            CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" />
                    </Border>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Trigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <ColorAnimation
                                        Storyboard.TargetName="bor1"
                                        Storyboard.TargetProperty="Background.Color"
                                        To="White"
                                        Duration="0:0:0.5" />
                                    <ColorAnimation
                                        Storyboard.TargetName="bor"
                                        Storyboard.TargetProperty="BorderBrush.Color"
                                        To="#FF32FAC8"
                                        Duration="0:0:0.5" />
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="dropdown" Storyboard.TargetProperty="Visibil
                                        <DiscreteObjectKeyFrame KeyTime="0:0:0.3">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.EnterActions>
                        <Trigger.ExitActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <ColorAnimation Storyboard.TargetName="bor1" Storyboard.TargetProperty="Background.Color" />
                                    <ColorAnimation Storyboard.TargetName="bor" Storyboard.TargetProperty="BorderBrush.Color" />
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="dropdown" Storyboard.TargetProperty="Visibil
                                        <DiscreteObjectKeyFrame KeyTime="0:0:0.3">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Collapsed</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.ExitActions>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

カスタム コントロールを使用する

<Grid>
    <local:Switch Width="100" Height="100" />
</Grid>

カスタム コントロールでよく使用されるナレッジ ポイント

  1. TemplatePart プロパティ

カスタム コントロールでは、書き換えられた OnApplyTemplate() メソッドで指定されたボタンを取得するなど、一部のコントロールには呼び出しを容易にする名前が必要です。これには、ユーザーがコントロールを使用するときにテンプレート内の名前を変更できないことが必要です。

//应用该控件时调用
public override void OnApplyTemplate()
{
    
    
    UpButtonElement = GetTemplateChild("UpButton") as RepeatButton;
    DownButtonElement = GetTemplateChild("DownButton") as RepeatButton;
}

したがって、クラスの前に属性を使用してマークを付けます

[TemplatePart(Name = "UpButton", Type = typeof(RepeatButton))]
[TemplatePart(Name = "DownButton", Type = typeof(RepeatButton))]
public class Numeric : Control{
    
    }
  1. 視覚状態の定義と呼び出し

視覚的な状態をカスタム コントロールで定義して、さまざまな状態で効果を表示できます。

XML で視覚的な状態を定義します。異なるグループの視覚的な状態は相互に排他的です。

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup Name="FocusStates">
        <VisualState Name="Focused">
            <Storyboard>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="FocusVisual" 
                           Storyboard.TargetProperty="Visibility" Duration="0">
                    <DiscreteObjectKeyFrame KeyTime="0">
                        <DiscreteObjectKeyFrame.Value>
                            <Visibility>Visible</Visibility>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>
        <VisualState Name="Unfocused"/>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

C# での対応する視覚状態の切り替え

private void UpdateStates(bool useTransitions)
{
    
    
    if (IsFocused)
    {
    
    
        VisualStateManager.GoToState(this, "Focused", false);
    }
    else
    {
    
    
        VisualStateManager.GoToState(this, "Unfocused", false);
    }
}

同時に、属性を使用してバックグラウンド クラスでマークを付けることができます。

[TemplateVisualState(Name = "Focused", GroupName = "FocusedStates")]
[TemplateVisualState(Name = "Unfocused", GroupName = "FocusedStates")]
public class Numeric : Control{
    
    }

実際、トリガーを使用してこの機能を実現できます。

ケーススタディのソースコードのダウンロード

ユーザー コントロールとカスタム コントロールのいくつかのケースを共有します。その効果は次のとおりです。

画像

ソースコードのダウンロード

おすすめ

転載: blog.csdn.net/weixin_44064908/article/details/128938443