kknaguib
kknaguib

Reputation: 749

WPF C#: UI won't update with even thou OnPropertyChanged is triggered

I don't get why my UI won't update even thou when I debug I can see that the number of records variable has been updated. I simply retrieve data from a database and I count the number of rows and I display it, it works fine on the window Load event but when I click on the refresh button the number doesn't update even thou the new row has been added. Here's my XAML:

<TextBlock Name="numRecordsAnalyzed_TAtab" TextWrapping="Wrap" Margin="0,-1,369,0" Grid.RowSpan="2" Grid.Column="1"> 
                        <Run Text="Records Found: " Foreground="{StaticResource Foreground}" FontSize="14"/>
                        <Run Text="{Binding Numrecords}" Foreground="LightBlue" FontSize="14"/>
</TextBlock>

Here's the C#:

    public partial class OpenTradesWindow : INotifyPropertyChanged
{
    private ScotiaTradeAnalyzerDb connection = null;
    ObservableCollection<TradesClass> collection;

    private int numOfrecords = 0;
    public event PropertyChangedEventHandler PropertyChanged;

    #region properties
    public class TradesClass
    {
        public DateTime TradeDate { get; set; }
        public TimeSpan TradeTime { get; set; }
        public DateTime? CloseDateTime { get; set; }
        public string ClientName { get; set; }
        public string CurPair { get; set; }
        public int Amnt { get; set; }
        public string Action { get; set; }
        public decimal ExecutedRate { get; set; }
    }

    public int Numrecords
    {
        get { return numOfrecords; }
        set
        {
            if (numOfrecords != value)
            {
                numOfrecords = value;
                OnPropertyChanged("Numrecords");
            }
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    public OpenTradesWindow(ScotiaTradeAnalyzerDb Connection)
    {
        InitializeComponent();
        this.WindowStartupLocation = WindowStartupLocation.Manual;
        this.connection = Connection;
    }

    private void OpenTradesLoaded(object sender, RoutedEventArgs e)
    {

        try
        {
            collection = new ObservableCollection<TradesClass>();

            var OpenTradesQuery = from qa in connection.QuickAnalyzerInputs
                                  where qa.TradeClosedDateTime == null && qa.TraderID == Environment.UserName
                                  select new TradesClass
                                  {
                                      TradeDate = qa.ClientTradedDate,
                                      TradeTime = qa.ClientTradedTime,
                                      CloseDateTime = qa.TradeClosedDateTime,
                                      ClientName = qa.ClientName,
                                      CurPair = qa.CurrencyPair,
                                      Amnt = qa.TradedAmount,
                                      Action = qa.Action,
                                      ExecutedRate = qa.ExecutedRate
                                  };


            if(OpenTradesQuery.Count() > 0)
            {
                numOfrecords = OpenTradesQuery.Count();
                DataContext = this;

                foreach (var item in OpenTradesQuery)
                {
                    collection.Add(item);
                }

                DG_openTrades.ItemsSource = collection;

            }
            else
            {
                MeBox.Show("You have no open trades.", "", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
        catch
        {
            MeBox.Show("Error retrieving data.", "Database Error", MessageBoxButton.OK, MessageBoxImage.Error);

        }


    }

    private void RefreshClick(object sender, RoutedEventArgs e)
    {
        try
        {
            collection = new ObservableCollection<TradesClass>();

            var OpenTradesQuery = from qa in connection.QuickAnalyzerInputs
                                  where qa.TradeClosedDateTime == null && qa.TraderID == Environment.UserName
                                  select new TradesClass
                                  {
                                      TradeDate = qa.ClientTradedDate,
                                      TradeTime = qa.ClientTradedTime,
                                      CloseDateTime = qa.TradeClosedDateTime,
                                      ClientName = qa.ClientName,
                                      CurPair = qa.CurrencyPair,
                                      Amnt = qa.TradedAmount,
                                      Action = qa.Action,
                                      ExecutedRate = qa.ExecutedRate
                                  };


            if (OpenTradesQuery.Count() > 0)
            {
                updateNumRecords(OpenTradesQuery.Count());

                foreach (var item in OpenTradesQuery)
                {
                    collection.Add(item);
                }

                DG_openTrades.ItemsSource = collection;

            }
            else
            {
                MeBox.Show("You have no open trades.", "", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
        catch
        {
            MeBox.Show("Error retrieving data.", "Database Error", MessageBoxButton.OK, MessageBoxImage.Error);

        }

    }

    private void updateNumRecords(int num)
    {
        numOfrecords = num;
    }

I tried putting the datacontext under the initialization but then it displays 0, so I placed it under the count in the Load event. Why won't the UI update when I click on the refresh button any suggestions?

Upvotes: 1

Views: 605

Answers (3)

paparazzo
paparazzo

Reputation: 45096

You are updating the backing property so Notify is not called

numOfrecords

You need to update

Numrecords

Why have a method just to update the property?
I would just do it directly.

Numrecords = OpenTradesQuery.Count();

If you insist on updating the backing property you can
(but that is what a set is for)

numOfrecords = OpenTradesQuery.Count();
NotifyPropertyChanged("Numrecords");

Upvotes: 5

Matt Davis
Matt Davis

Reputation: 46034

In your refresh callback, you're updating the variable directly, not through the property. Thus, the PropertyChanged event is not being fired. Change updateNumRecords to:

private void updateNumRecords(int num)
{
    Numrecords = num;
}

I do agree w/ @Blam, though. There doesn't seem to be a pressing need for this method. Just put it inline inside RefreshClick like he suggested.

Upvotes: 1

Paul Lydon
Paul Lydon

Reputation: 1048

You are setting the field 'numOfrecords' rather than the Property 'Numrecords' so the OnPropertyChanged() is not called.

Upvotes: 0

Related Questions