をバインドするDataContext
と、バインドがUserControl
正しく機能します。DataContext
プログラムをデバッグすると、 のUserControl
が正しい にバインドされていることがわかりますViewModel
。ただし、 で特定のプロパティ (テキスト ボックスなど) にバインドするとUserControl
、ViewModel
何かが失敗します。はの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 スニペットはページ全体を表し、このページDataContext
はParentViewModel
. このページには、で公開されているプロパティに関連付けられUserControl
たバインディングを持つ が含まれています。DataContext
ChildViewModel
ParentViewModel
<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>
ChildView
XAML は非常に簡単です。Name
のプロパティにバインドされたテキスト ボックスがありますChildViewModel
。明確にするために、上記のスニペットで既にバインドされているため、DataContext
何もバインドしません。ChildView
<UserControl ... >
<StackPanel>
<!-- Binding to the Name property -->
<TextBox Text="{Binding Name}"/>
</StackPanel>
</UserControl>
このアプローチがうまくいかない理由を誰かが教えてくれたら、私はあなたの答えに賛成票を投じて「ありがとう!」と言います。