views:

199

answers:

1

I have a Silverlight ModelViewViewModel project that I would like to expose a property on the view model to a UserControl like:

public DTO.Client Client
{
    get { return client; }
}

client is a private backing variable that I set in a async completed event handler:

    void GetClientByIDComplete(object sender, GetClientByIDCompletedEventArgs e)
    {
        Application.Current.RootVisual.Dispatcher.BeginInvoke(() =>
        {
            DTO.Client c = new ServiceContract.DTO.Client();
            c = e.Result as DTO.Client;
            client = e.Result as DTO.Client;
        });
    }

In my Silverlight page I have the following:

<TextBlock Text="{Binding Client.Name}"/>

The data never is displayed. The data is displayed if I change the property to:

public DTO.Client Client
{
    get { 
          client.Name = "My Name";
          return client; }
}

This way I explicitly assign the value.

What do I have to change so the property is seen by my page?

A: 

Are you setting the data context after Client is populated, or before?

After it should definately display, before, it will not know the underlying data has changed without adding additional code, implement INotifyPropertyChanged so that bindings can understand the data has altered.

Andrew
I set the DataContext in the XAML of the page: <UserControl.Resources> <viewmodel:ClientViewModel x:Key="viewModel"/> </UserControl.Resources> <Grid x:Name="LayoutRoot" DataContext="{StaticResource viewModel}">Then bind the object property to the control:<TextBlock Text="{Binding Client.Name}"/>
The XAML is declarative so that static resource will be resolved on load, whilst the actual data is lazy loaded out of the WCF service. The page is not aware that the underlying data has altered unless it gets a notification.I would make the async call and set the data context at run time when you get the object back for ease.
Andrew
Since I am using a ViewModel which is unaware of the page, how would I set the DataContext? Maybe instead of assigning the object which the WCF service returns(which should implement INotifyPropertyChanged) to a property on the ViewModel, the object should be returned to the calling page through an event??
It is the other way around, the View has it's data context set to be the view model. In the code behind the view, set the data context up.Then the view model can issue notifications and make calls as appropriate.
Andrew
As it turns out, I had the DataContext set incorrectly. Thanks for pointing me in the right direction.