使用WCF的Windows 10 UWP绑定控件

时间:2017-01-03 16:25:13

标签: c# windows wcf uwp

我是UWP的新手,在从MS SQL数据库中抓取绑定数据时遇到问题。

我有一个简单的视图模型,我通过使用WCF合约来填充;

    public async Task<User> LoadData()
    {
        UserDataFunctions functions = new UserDataFunctions();
        usr = await functions.GetUserDetails();
        return usr; 
    }

我尝试使用类似于

的东西在OnNavigateTo中填充我的View模型
    await ViewModel.LoadData();

并绑定为;

<TextBox Text="{x:Bind ViewModel.firstname, Mode=TwoWay}" Name="userID"/>

但是,即使从SQL Server正确返回数据,它也永远不会绑定到控件。

如果我执行以下操作,它会按预期工作;

this.userID.Text = u.firstname;

我无法为我的生活找出我所缺少的东西。

3 个答案:

答案 0 :(得分:0)

OK ...基于提供的Xaml标记和c#代码,您似乎正在使用OnNavigatedTo事件来触发代码隐藏中声明的视图模型的LoadData方法。假设viewmodel中至少有一个名为“firstname”的字符串类型的属性,而viewmodel实现了INotifyPropertyChanged。

如果我推断正确,

LoadData返回Task<User> - 所以在您的代码中,当您等待任务时,它将返回User对象 - 这就是设置文本值的原因。

您的文本框绑定到ViewModel的firstname属性,因此您需要在检索User对象时设置该值。没有理由将其返回到后面的代码中。

public async Task LoadData()
{
    UserDataFunctions functions = new UserDataFunctions();
    //not sure what usr is???
    usr = await functions.GetUserDetails();
    //set viewmodel firstname property
    firstname = usr.firstname; 
}

答案 1 :(得分:0)

在没有看到代码隐藏的情况下,我最近遇到的一个问题就是确定如何在代码隐藏中定义它,以便XAML可以访问它。

在View.xamls.cs中:

public MyViewModelClass ViewModel {get; set;}

public View()
{
    this.InitializeComponent();

    ViewModel = new MyViewModelClass();
}

然后在XAML中调用它就像你一样:

<TextBox Text="{x:Bind ViewModel.firstname, Mode=TwoWay}" Name="userID"/>

答案 2 :(得分:0)

您无法在初始加载时看到数据,因为DataContext未设置为绑定。您需要让XAML知道数据的来源。

从视图模型接收数据后添加以下行。

User data = await ViewModel.LoadData();
this.DataContext = data;

你的XAML将是

<TextBox Text="{x:Bind firstname, Mode=TwoWay}" Name="userID"/>