.Net Framework WPF

WPF DependencyProperty 簡易サンプル

2017年9月16日

WPF の DependencyProperty を簡単に実装したサンプルコードです。

C# コード
TextBox クラスを継承した MyTextBox クラスを定義し、string 型の MyProperty を用意します。DependencyProperty.Register メソッドの引数 FrameworkPropertyMetadata から、デフォルト値(今回は null)とデフォルトのバインドモード(今回は TwoWay)を設定します。

public class MyTextBox : TextBox
{
public string MyProperty
{
get { return (string)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}

// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register(
"MyProperty",
typeof(string),
typeof(MyTextBox),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
}

XAML コード
XAML 側では、MyTextBox の MyProperty プロパティを、自身の Text プロパティと、別に用意した TextBox の Text プロパティにバインドしています。

<StackPanel Orientation="Vertical">
<local:MyTextBox x:Name="myTextBox1" Text="{Binding MyProperty, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}" MyProperty="This is my property."/>
<TextBox Text="{Binding ElementName=myTextBox1, Path=MyProperty, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>

-.Net Framework, WPF