for WPF developers
添付プロパティとは、既存のコントロールに後付けで新たに添付することができるプロパティのことです。 例えば Grid コントロールは Grid.Row 添付プロパティなどを使って子要素の配置をおこなっていますが、 Grid.Row 添付プロパティは Grid コントロールにのみ設定するプロパティではなく、 Button コントロールや TextBlock コントロールなどその他の既存のコントロールに添付できます。 これと同じものが自分でも作成できます。
ページ内リンク
添付プロパティを作成するためにはそのプロパティを持つクラスが必要ですが、
一般的にはその目的に関する名前を付けます。
ここではサンプルとして作成するので、SampleAttachedProperties という名前のクラスにします。
そして、このクラスに IsFirst 添付プロパティを追加します。
namespace CustomAttachedProperty { using System.Windows; public class SampleAttachedProperties { public static readonly DependencyProperty IsFirstProperty = DependencyProperty.RegisterAttached("IsFirst", typeof(bool), typeof(SampleAttachedProperties), new FrameworkPropertyMetadata(false)); public static bool GetIsFirst(DependencyObject target) { return (bool)target.GetValue(IsFirstProperty); } public static void SetIsFirst(DependencyObject target, bool value) { target.SetValue(IsFirstProperty, value); } } }
上記で作成した添付プロパティを XAML 上で設定するときは次のようにします。
<Window x:Class="CustomAttachedProperty.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:core="clr-namespace:CustomAttachedProperty" Title="MainView" Height="300" Width="300"> <Grid> <StackPanel> <Button x:Name="button1" Content="1st Button" core:SampleAttachedProperties.IsFirst="True" /> <Button x:Name="button2" Content="2nd Button" core:SampleAttachedProperties.IsFirst="False" /> <Button x:Name="button3" Content="3rd Button" core:SampleAttachedProperties.IsFirst="False" /> </StackPanel> </Grid> </Window>
コードから設定された添付プロパティの値を取得するには次のようにします。
// IsFirst 添付プロパティの取得 var isFirst = SampleAttachedProperties.GetIsFirst(this.button1); // IsFirst 添付プロパティの設定 SampleAttachedProperties.SetIsFirst(this.button2, true);
一般的に添付プロパティはこれだけで使用することはありません。 というのも、Code 3 を見るとわかるように、これは View のコードビハインドに記述しています。 添付プロパティは添付ビヘイビアで利用することでその効果を発揮します。
Designed by CSS.Design Sample