繁体   English   中英

在XAML中绑定UserControl的DataContext不起作用(Windows Phone)

[英]Binding the DataContext of a UserControl in XAML is not working (Windows Phone)

当我绑定UserControlDataContext ,绑定正常工作。 当我调试程序时,我可以看到UserControlDataContext绑定到正确的ViewModel 但是,当我将UserControl中的特定属性(如文本框)绑定到ViewModel ,某些操作会失败。 UserControl将正确获取ViewModel的初始值。 如果我有一些绑定字符串属性,默认值为“test”,则UserControl会正确显示。 但是,没有任何更改会传播回ViewModel 因此,在最初显示“test”的文本框中输入“abcd”不会将ViewModel更新为“abcd”。 ViewModel错误地包含“test”字符串。

如果上述内容不清楚或不够具体,请继续。 我将使用代码和XAML片段来布置我的架构。

我有一个聚合其他虚拟机的虚拟机。 在此父虚拟机中,子虚拟机作为可绑定属性公开。

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 ,或者没有。

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 ,它具有与ParentViewModel公开的ChildViewModel属性关联的DataContext绑定。

<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非常简单。 有一个文本框绑定到ChildViewModelName属性。 为了清楚ChildView ,我没有在ChildView绑定任何DataContext ,因为它已经绑定在上面的代码片段中。

<UserControl ... >

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

</UserControl> 

如果有人能告诉我为什么这种方法不起作用,我会提出你的答案并说“谢谢!”。

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

将绑定模式设置为TwoWay将允许View更新ViewModel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM