コントロールのプロパティを XAML で変更できるように、DependencyProperties を使用して簡単な UserControl の例を作成しています (以下のコード)。
しかし、もちろん、私のアプリケーションでは、このコントロールに密結合のコード ビハインドを持たせたくありません。代わりに、ユーザー コントロールは "DataTypeWholeNumberView" というビューになり、"DataTypeWholeNumberViewModel" という独自の ViewModel を持ちます。
したがって、以下の DependencyProperty ロジックを ViewModel に実装しますが、ViewModel では通常 INotifyPropertyChanged を継承します。これにより、同じ機能が得られるようです。
では、次の関係はどのようなものですか。
- UserControl XAML の DataContext をDependencyProperties を持つそのコード ビハインドにバインドする
- UserControl XAML (View) の DataContext をそのViewModel (INotifyPropertyChanged から継承) にバインドし、INotifyPropertyChanged 機能を実装するプロパティを持っていますか?
XAML:
<UserControl x:Class="TestDependencyProperty827.SmartForm.DataTypeWholeNumber"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Horizontal">
<TextBlock Text="{Binding Label}"/>
</StackPanel>
</StackPanel>
</UserControl>
コードビハインド:
using System.Windows;
using System.Windows.Controls;
namespace TestDependencyProperty827.SmartForm
{
public partial class DataTypeWholeNumber : UserControl
{
public DataTypeWholeNumber()
{
InitializeComponent();
DataContext = this;
}
public string Label
{
get
{
return (string)GetValue(LabelProperty);
}
set
{
SetValue(LabelProperty, value);
}
}
public static readonly DependencyProperty LabelProperty =
DependencyProperty.Register("Label", typeof(string), typeof(DataTypeWholeNumber),
new FrameworkPropertyMetadata());
}
}