.Net Framework WPF

WPF 依存関係プロパティ

2016年11月21日

こちらのサイトを参考にさせていただき、依存関係プロパティ作成の練習をしてみました。
ソースコードは下記サイトの方のものと非常に似たものになってしまいました...。

tips - 独自の依存関係プロパティを作成する
http://yujiro15.net/YKSoftware/tips_DependencyProperty.html

LabelInput.xaml.cs

"propdp" と入力し、Tab を2回押すとスニペットが自動で挿入されて雛形が出来上がります。プロパティの型情報、名前、プロパティを所有するクラス、プロパティのデフォルト値をそれぞれ変更していきます。PropertyMetadata の第1引数にはデフォルト値を、第2引数にはプロパティの変更通知を捕捉することができます。

public partial class LabelInput : UserControl
{
public LabelInput()
{
InitializeComponent();
}

public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}

// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(LabelInput), new PropertyMetadata("Text", TextChanged));

private static void TextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{

}


public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}

// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string), typeof(LabelInput), new PropertyMetadata("Value", ValueChanged));

private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{

}
}

LabelInput.xaml

Text プロパティと Value プロパティには、バインディングで外部から設定される値を参照しています。

<UserControl x:Class="MyPropertyTest.LabelInput"
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"
xmlns:local="clr-namespace:MyPropertyTest"
mc:Ignorable="d" Height="24.812" Width="173.684">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="28*"/>
<ColumnDefinition Width="59*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="label"
Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:LabelInput}}, StringFormat='{}{0} : '}"
Grid.Column="0"/>
<TextBox x:Name="textBox"
TextWrapping="Wrap"
Text="{Binding Value, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:LabelInput}}}"
Grid.Column="1"/>

</Grid>
</UserControl>

MainWindow.xaml

Text プロパティと Value プロパティの設定例です。

<local:LabelInput HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="名前"
Value="としひこ"/>
<local:LabelInput HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="名前"
Value="よしひこ" Width="174" Margin="0,25,0,0"/>

-.Net Framework, WPF