LoginSignup
9

More than 5 years have passed since last update.

添付プロパティと依存関係プロパティの違い

Last updated at Posted at 2019-01-22

実装

添付プロパティ

  • 初期化にはDependencyProperty.RegisterAttached()を使う。
  • セッター(SetXXX())とゲッター(GetXXX())が必要。
  • xamlで参照する際は、クラス名を含めてプロパティを指定する。
添付プロパティ
using System.Windows;

namespace Sample {
    public class AttachedXXX {
        public static DependencyProperty XXXProperty
            = DependencyProperty.RegisterAttached(
                "XXX",
                typeof(bool),
                typeof(AttachedXXX),
                new PropertyMetadata()
            );

        public static void SetXXX(DependencyObject obj, bool value)
            => obj.SetValue(XXXProperty, value);

        public static bool GetXXX(DependencyObject obj)
            => (bool)obj.GetValue(XXXProperty);
    }
}
XAML
<Window x:Class="Sample.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Sample"
        Title="MainView" Height="300" Width="300">
    <Grid>
        <TextBox local:AttachedXXX.XXX="False" />
    </Grid>
</Window>

依存関係プロパティ

  • DependencyObjectクラスを継承している必要がある。
  • 初期化にはDependencyProperty.Register()を使う。
  • 同名のプロパティを定義する。
依存関係プロパティ
using System.Windows;

namespace Sample {
    //UserControlはDependencyObjectを継承している
    public class MyControl : UserControl {
        public static DependencyProperty XXXProperty
            = DependencyProperty.Register(
                nameof(XXX),
                typeof(bool),
                typeof(MyControl),
                new PropertyMetadata()
            );

        public bool XXX {
            get { return (bool)GetValue(XXXProperty); }
            set { SetValue(XXXProperty, value); }
        }
    }
}
XAML
<Window x:Class="Sample.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Sample"
        Title="MainView" Height="300" Width="300">
    <Grid>
        <local:MyControl XXX="False" />
    </Grid>
</Window>

使い道

添付プロパティ

  • 既存のUI要素にプロパティ(ビヘイビア)を付与する。

依存関係プロパティ

  • 複雑なビューをUserControlとして切り出した際に、内部のパラメータをプロパティとして公開する。
  • Behaviorクラスの派生クラスにプロパティを追加する。

まとめ

  • プロパティそのものを独立させることで、継承せずにプロパティを追加できるようにしたのが添付プロパティ。
  • DependencyObjectクラスを継承して作ったクラスに、バインディング可能なプロパティを追加するのが依存関係プロパティ。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9