【问题标题】:WinRT - XAML binding DataContextWinRT - XAML 绑定 DataContext
【发布时间】:2014-03-09 01:45:32
【问题描述】:

我尝试将ObservableCollection<UserProfile> UsersList 绑定到页面DataContext,但程序一直告诉我,他找不到UsersList,尽管我可以使用Debug.WriteLine 在OutPut 中看到它的值。 但另一方面,如果我在 C# 代码中添加DataContext,一切都会完美运行。 我做错了什么?

C#代码:

this.DataContext = new UsersViewModel(); //inside MainPage constructor

XAML 代码:

DataContext="{Binding UsersViewModel, RelativeSource={RelativeSource Self}}" //inside <page .../>

【问题讨论】:

    标签: c# xaml windows-store-apps datacontext


    【解决方案1】:

    尝试以这种方式设置绑定:

    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    

    您当前的绑定意味着,将数据上下文绑定到一个名为UsersViewModel 的属性,该属性在其中声明。例如,如果你在后面的代码中有这样的东西,那将起作用:

    public UsersViewModel UsersViewModel { get; set; }
    

    然后 DataContext 将被设置为该属性。

    更新:

    看看你的答案,你可以尝试这样做在页面级别设置 DataContext :

    <Page.DataContext>
        <local:UsersViewModel />
    </Page.DataContext>
    

    【讨论】:

    • 是的,我刚才试过了,但还是没有。我什至将 UsersViewModel 对象名称更改为其他名称。
    • 对不起,我误解了你的情况。如果您想将 DataContext 设置为代码隐藏,我的第一个 sn-p 工作。尝试将您的绑定保持为已发布和问题,并拥有一个名为 UsersViewModel 的属性,如我的第二个 sn-p 所示。然后在构造函数中初始化属性:UsersViewModel View = new UsersViewModel();
    • 确实也是这样。万分感谢。我认为,我的解决方案更好,当您希望将不同的对象绑定到不同的元素时,我对吗?但是如果整个页面只需要一个绑定,您可以简单地绑定到页面。
    • 此方法也适用于对象/UI 控制级别。它与使用 Resources 的不同之处在于,Resources 可以通过它的 Key 属性从多个控件中访问。因此,您可以将多个控件绑定到在 Resource 中声明的一个视图模型,不能使用此答案中的方法。
    【解决方案2】:

    UserViewModel 应该是后面 MainPage.xaml.cs 代码中的可访问对象。你可以有类似的东西

    public UsersViewModel UsersViewModel { get {return _usersViewModel; } private set { _usersViewModel = value;} }
    

    你必须使用对象名而不是类名。

    【讨论】:

    • 好的,我现在改成:public UsersViewModel View = new UsersViewModel(),但还是一样...
    • @Klemzy 这不起作用,因为您将其声明为字段/成员而不是属性。绑定仅适用于属性。
    【解决方案3】:

    好的,我现在可以使用它了,但在这种情况下,我不会在页面本身上绑定任何东西,而是在网格上。

    <Page.Resources>
        <local:UsersViewModel x:Key="UsersViewModel" />
    </Page.Resources>
    
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" DataContext="{StaticResource UsersViewModel}">
    

    这是好的解决方案吗?

    【讨论】:

    • 我认为这是可以接受的。检查我更新的答案,以使用类似的方法在页面级别绑定数据上下文,看看这是否也适合您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2013-02-19
    • 2012-10-14
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多