ビューモデル パターンを使用しているため、カスタム ユーザー コントロールの DataContext は、実際には実際のデータのビューモデル ラッパーです。
カスタム コントロールには、カスタム コントロールの階層インスタンスを含めることができます。
実際のデータのカスタム コントロールに DependencyProperty を設定し、バインドによって設定されたときにそのデータの新しいビューモデルを作成し、ユーザー コントロールのデータ コンテキストを新しいビューモデルに設定することを期待しています。ただし、DataContext プロパティを設定すると、実際のデータ DependencyProperty が無効になり、null に設定されるようです。これを回避する方法、またはビューモデルを使用する適切な方法を知っている人はいますか?
私がやろうとしていることのトリミングされたサンプル:
ユーザー コントロール:
public partial class ArchetypeControl : UserControl
{
public static readonly DependencyProperty ArchetypeProperty = DependencyProperty.Register(
"Archetype",
typeof(Archetype),
typeof(ArchetypeControl),
new PropertyMetadata(null, OnArchetypeChanged)
);
ArchetypeViewModel _viewModel;
public Archetype Archetype
{
get { return (Archetype)GetValue(ArchetypeProperty); }
set { SetValue(ArchetypeProperty, value); }
}
private void InitFromArchetype(Archetype newArchetype)
{
if (_viewModel != null)
{
_viewModel.Destroy();
_viewModel = null;
}
if (newArchetype != null)
{
_viewModel = new ArchetypeViewModel(newArchetype);
// calling this results in OnArchetypeChanged getting called again
// with new value of null!
DataContext = _viewModel;
}
}
// the first time this is called, its with a good NewValue.
// the second time (after setting DataContext), NewValue is null.
static void OnArchetypeChanged( DependencyObject obj, DependencyPropertyChangedEventArgs args )
{
var control = (ArchetypeControl)obj;
control.InitFromArchetype(args.NewValue as Archetype);
}
}
ビューモデル:
class ArchetypeComplexPropertyViewModel : ArchetypePropertyViewModel
{
public Archetype Value { get { return Property.ArchetypeValue; } }
}
XAML:
<Style TargetType="{x:Type TreeViewItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding ViewModelType}" Value="{x:Type c:ArchetypeComplexPropertyViewModel}">
<Setter Property="Template" Value="{StaticResource ComplexPropertyTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
<ControlTemplate x:Key="ComplexPropertyTemplate" TargetType="{x:Type TreeViewItem}">
<Grid>
<c:ArchetypeControl Archetype="{Binding Value}" />
</Grid>
</ControlTemplate>
この問題は、Cannot databind DependencyPropertyのコメントで言及されていましたが、解決されませんでした