1

ビューモデル パターンを使用しているため、カスタム ユーザー コントロールの 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のコメントで言及されていましたが、解決されませんでした

4

1 に答える 1

1

これを行うことにより:

<c:ArchetypeControl Archetype="{Binding Value}" />

プロパティをデータ コンテキストでArchetype呼び出されるプロパティにバインドしています。Valueデータ コンテキストを新しいものに変更することArchetypeViewModelで、バインディングの新しい評価を効果的に引き起こします。ArchetypeViewModel新しいオブジェクトに null 以外のプロパティがあることを確認する必要がありValueます。

あなたのコード (具体的には と の定義ArchetypeComplexPropertyViewModel)ArchetypePropertyViewModelを詳しく見ないと、この原因が何かはわかりません。

于 2010-01-11T10:12:03.790 に答える