当我绑定(bind) DataContext
的 UserControl
绑定(bind)正常工作。当我调试程序时,我可以看到 DataContext
的UserControl
绑定(bind)到正确的 ViewModel
.但是,当我绑定(bind)到 UserControl
中的特定属性(如文本框)时到ViewModel
,有些事情失败了。 UserControl
将获取 ViewModel
的初始值正确。如果我有一些默认值为“test”的绑定(bind)字符串属性,UserControl
正确显示。但是,没有任何更改传播回 ViewModel
。 .所以在原来显示“test”的文本框中输入“abcd”不会更新ViewModel
到“abcd”。 ViewModel
错误地包含“测试”字符串。
如果上述内容不清楚或不够具体,请继续。我将使用代码和 XAML 片段来布置我的体系结构。
我有一个聚合其他虚拟机的虚拟机。在此父虚拟机中,子虚拟机作为可绑定(bind)属性公开。
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);
}
}
//...
}
ChildViewModel
是您的典型 VM,它公开了一些其他属性,例如 Strings
我想绑定(bind)到一个文本框或什么不是。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
绑定(bind)到 ParentViewModel
.此页面包含 UserControl
其中有一个 DataContext
与 ChildViewModel
关联的绑定(bind)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 非常简单。有一个文本框绑定(bind)到 Name
ChildViewModel
中的属性(property).为了清楚起见,我不绑定(bind)任何 DataContext
在 ChildView
因为它已经绑定(bind)在上面的代码片段中。<UserControl ... >
<StackPanel>
<!-- Binding to the Name property -->
<TextBox Text="{Binding Name}"/>
</StackPanel>
</UserControl>
如果有人能告诉我为什么这种方法不起作用,我会支持你的回答并说“谢谢!”。
最佳答案
<TextBox Text ="{Binding Name,
Mode=TwoWay}"/>
设置绑定(bind)模式为
TwoWay
会让View
更新 ViewModel
.
关于c# - 在 XAML 中绑定(bind) UserControl 的 DataContext 不起作用(Windows Phone),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12754514/