How to set DataContext without clearing dependency properties?
我使用的是viewmodel模式,因此我用于自定义用户控件的DataContext实际上是实际数据的viewmodelpackage器。
我的自定义控件可以包含该自定义控件的层次结构实例。
我在自定义控件中为实际数据创建了DependencyProperty,希望通过绑定设置后为该数据创建一个新的视图模型,然后将用户控件的datacontext设置为新的视图模型。但是,似乎设置DataContext属性会导致我的真实数据DependencyProperty无效并设置为null。有谁知道解决这个问题的方法,或者更确切的说我应该使用viewmodels?
我正在尝试做的修剪样本:
用户控件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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); } } |
视图模型:
1 2 3 4 | class ArchetypeComplexPropertyViewModel : ArchetypePropertyViewModel { public Archetype Value { get { return Property.ArchetypeValue; } } } |
XAML:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <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> |
在无法对DependencyProperty进行数据绑定的注释中提到了此问题,但从未解决
这样做:
1 | <c:ArchetypeControl Archetype="{Binding Value}" /> |
您正在将您的
没有看到更多的代码(特别是