WPF C#:即使触发了OnPropertyChanged,UI也不会更新

时间:2014-03-06 14:44:05

标签: c# wpf user-interface

我不知道为什么我的UI在我调试时不会更新我可以看到记录变量的数量已经更新。我只是从数据库中检索数据并计算行数并显示它,它在窗口Load事件上工作正常,但是当我点击刷新按钮时,即使添加了新行,数字也不会更新。这是我的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>

这是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;
    }

我尝试将datacontext置于初始化状态,但随后显示0,因此我将其置于Load事件的计数之下。当我点击刷新按钮时,为什么UI不会更新?

3 个答案:

答案 0 :(得分:5)

您正在更新支持属性,因此不会调用Notify

numOfrecords

您需要更新

Numrecords

为什么有方法只是更新属性?
我会直接这样做。

Numrecords = OpenTradesQuery.Count();

如果您坚持要更新支持属性,您可以 (但这就是一套)

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

答案 1 :(得分:1)

在刷新回调中,您直接更新变量,而不是通过属性。因此,PropertyChanged事件未被触发。将updateNumRecords更改为:

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

我确实同意@Blam。似乎没有迫切需要这种方法。就像他建议的那样把它放在RefreshClick里面。

答案 2 :(得分:0)

您正在设置字段'numOfrecords'而不是Property'Numrecords',因此不会调用OnPropertyChanged()。