Callback not binding correctly

2019-08-18 06:15发布

问题:

In the code below, the UnitOccupierDetails collection binds correctly but the OwnersCountString doesn't. Can anyone explain why? This code is in my ViewModel:

private void BindSelectedStructure(object param) 
    { 
        UnitOccupierDetails.Clear(); 
        Structure selectedStructure = (Structure)param; 
        this.SelectedStructure = selectedStructure; 

        int StructureID = selectedStructure.IDStructure; 
        loadOwners = context.Load<UserOccupier>(context.GetUnitOccupierDetailsQuery(StructureID), OwnersLoadedCallback, false); 
    } 

    private void OwnersLoadedCallback(LoadOperation<UserOccupier> op) 
    { 
        int Counter = 0; 
        foreach (var item in op.Entities) 
        { 
            Counter++; 
            UnitOccupierDetails.Add(item as UserOccupier); 
        } 

        OwnersCountString = "Owners(" + Counter.ToString() + ")"; 
    }

And the XAML:

     <TextBlock Text='{Binding OwnersCountString,Source={StaticResource ViewModel},Mode=OneWay}'></TextBlock

OwnersCountStringProperty:

private string _ownersCountString;
    public string OwnersCountString
    {
        get { return _ownersCountString; }
        set { _ownersCountString = value; RaisePropertyChanged("OwnersCountString"); }
    }

回答1:

Your callback is not occurring on the UI thread. That means that the change is happening, but the UI has not updated itself on the thread that displays changes.

Here is our example from another of my answers. Our version of SendPropertyChanged (replace your RaisePropertyChanged) makes sure any code is executed on the UI thread:

protected delegate void OnUiThreadDelegate();

public event PropertyChangedEventHandler PropertyChanged;

public void SendPropertyChanged(string propertyName)
{
    if (this.PropertyChanged != null)
    {
        this.OnUiThread(() => this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
    }
}

protected void OnUiThread(OnUiThreadDelegate onUiThreadDelegate)
{
    if (Deployment.Current.Dispatcher.CheckAccess())
    {
        onUiThreadDelegate();
    }
    else
    {
        Deployment.Current.Dispatcher.BeginInvoke(onUiThreadDelegate);
    }
}