简体   繁体   中英

Windows 10 UWP Bind Controls using WCF

I'm new to UWP and am having problems grasping binding data from a MS SQL database.

I have a simple View Model that I populate by consuming a WCF contract;

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

I have tried populating my View Model in OnNavigateTo using something similar to;

    await ViewModel.LoadData();

And binding as;

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

However, even though the data is correctly returned from SQL Server, it never binds to the control.

If I do the following, it works as expected;

this.userID.Text = u.firstname;

I just cannot for the life of me figure out what I'm missing.

OK... Based on the Xaml markup and c# code provided, it appears that you are using the OnNavigatedTo event to fire the LoadData method of a viewmodel that is declared in your codebehind. It is assumed that there is at least a property of string type called "firstname" in the viewmodel and the viewmodel implements INotifyPropertyChanged.

If I inferred correctly,

The LoadData returns a Task<User> - so in your code behind, when you await the Task, it will return the User object - this is why setting the text value works.

Your textbox is bound to the firstname property of the ViewModel, so you need to set that value upon retrieving the User object. There is no reason to return it to the code behind.

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

Without seeing the codebehind, an issue I had recently since I'm also new, is determining how to define it in the codebehind so XAML can access it.

In View.xamls.cs:

public MyViewModelClass ViewModel {get; set;}

public View()
{
    this.InitializeComponent();

    ViewModel = new MyViewModelClass();
}

Then in XAML just call it like you do:

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

You are not able to see the data on initial load because DataContext is not set for binding. You need to let your XAML know where your data is coming from.

Add below line after receiving data from your view model.

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

and your XAML will be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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