1

をバインドするDataContextと、バインドがUserControl正しく機能します。DataContextプログラムをデバッグすると、 のUserControlが正しい にバインドされていることがわかりますViewModel。ただし、 で特定のプロパティ (テキスト ボックスなど) にバインドするとUserControlViewModel何かが失敗します。はのUserControl初期値をViewModel正しく取得します。デフォルト値が「test」のバインディング文字列プロパティがある場合、UserControlこれは正しく表示されます。ただし、変更が に反映されることはありませんViewModel。そのため、最初に「test」と表示されていたテキスト ボックスに「abcd」と入力しても、「abcd」に更新ViewModelされません。にはViewModel、「テスト」文字列が誤って含まれています。

上記が不明確または十分に具体的でない場合は、続行してください。コードと XAML スニペットを使用してアーキテクチャをレイアウトします。

他の VM を集約する VM があります。この親 VM では、子 VM がバインド可能なプロパティとして公開されます。

public class ParentViewModel : ViewModel
{
    #region Binding Properties

    private const string ChildViewModelPropertyName = "ChildViewModel";
    private ChildViewModel childViewModel = new ChildViewModel();
    public ChildViewModel ChildViewModel 
    {
        get { return this.childViewModel ; } 
        set
        {
            if (value == this.childViewModel )
            {
                return;
            }
            this.childViewModel = value;
            RaisePropertyChanged(ChildViewModelPropertyName);
        }
    }

    //... 
}

これは典型的な VM であり、テキスト ボックスにバインドしたいChildViewModelなどの他のプロパティを公開します。Strings

public class ChildViewModel : ViewModel
{
    #region Binding Properties

    private const string NamePropertyName = "Name";
    private string name = "";
    public string Name
    {
        get { return this.name; }
        set
        {
            if (value == this.name)
            {
                return;
            }
            this.name = value;
            RaisePropertyChanged(NamePropertyName);
        }
    }

    //...
}

XAML に。最初の XAML スニペットはページ全体を表し、このページDataContextParentViewModel. このページには、で公開されているプロパティに関連付けられUserControlたバインディングを持つ が含まれています。DataContextChildViewModelParentViewModel

<phone:PhoneApplicationPage ...>

   <!-- Sets the DataContext for the page. -->
   <phone:PhoneApplicationPage.DataContext>
        <vm:ParentViewModel/>
   </phone:PhoneApplicationPage.DataContext>

   <ScrollViewer>
       <phone:Pivot>
           <phone:PivotItem>
               <!-- ChildView is the UserControl whose DataContext should be bound to ChildViewModel -->
               <view:ChildView DataContext="{Binding ChildViewModel}"/>
           </phone:PivotItem>
       </phone:Pivot>
   </ScrollViewer>

</phone:PhoneApplicationPage>

ChildViewXAML は非常に簡単です。Nameのプロパティにバインドされたテキスト ボックスがありますChildViewModel。明確にするために、上記のスニペットで既にバインドされているため、DataContext何もバインドしません。ChildView

<UserControl ... >

    <StackPanel>
        <!-- Binding to the Name property -->
        <TextBox Text="{Binding Name}"/>
    </StackPanel>

</UserControl> 

このアプローチがうまくいかない理由を誰かが教えてくれたら、私はあなたの答えに賛成票を投じて「ありがとう!」と言います。

4

1 に答える 1

3
<TextBox Text ="{Binding Name,
                Mode=TwoWay}"/>

バインディング モードを に設定すると、 updateが実行TwoWayされます。ViewViewModel

于 2012-10-06T09:28:25.237 に答える