简体   繁体   中英

DataGrid is not bound to the ObservableCollection

I have a button in my view that execute this method in the ViewModel:

public void GetAudits(Guid? userId, DateTime? from, DateTime? to, string form)
        {
            StringBuilder sCondition = new StringBuilder("WHERE 0=0");

            if (userId != null && userId != Guid.Empty)
                sCondition.Append(string.Format(" AND UserId = '{0}' ", userId));

            if (!string.IsNullOrEmpty(form))
                sCondition.Append(string.Format(" AND FormName = '{0}' ", form));


            string query = string.Format("SELECT * FROM Common.TbHistoryLog {0}", sCondition);
            Audits = new ObservableCollection<HistoryLog>(oContext.Database.SqlQuery<HistoryLog>(query).ToList());

        }

the Audits property:

 public ObservableCollection<HistoryLog> Audits
    {
        get
        {
            return audits;
        }
        set
        {
            audits = value;
        }
    }
    ObservableCollection<HistoryLog> audits;

and this is the handler for the button:

private void BtnSearch(object sender, RoutedEventArgs e)
        {
            var userId = ((TbUsers)cmbUsers.SelectedItem)?.UserId;
            var from = dtFromDate.Value;
            var to = dtToDate.Value;
            var form = ((BlCommon.TbObjects)cmbForms.SelectedItem)?.ObjectRealName;
            using (ClsUserTransactions oUserTrans = new ClsUserTransactions())
            {
                oUserTrans.GetAudits(userId, from, to, form);
            }
        }

but when I click the button, the dataGrid doesn't get updated with the Audits collection:

<DataGrid  Name="gvHistory" Grid.Column="0" Grid.Row="9" Margin="2" Visibility="Visible" ItemsSource="{Binding Audits}" Grid.ColumnSpan="8" IsReadOnly="True" Grid.RowSpan="2"  AutoGenerateColumns="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CanUserAddRows="False"/>

When I debug, I notice that the getter block is not hit

Why don't you simply clear and re-populate the same ObservableCollection ?:

public void GetAudits(Guid? userId, DateTime? from, DateTime? to, string form)
{
    StringBuilder sCondition = new StringBuilder("WHERE 0=0");

    if (userId != null && userId != Guid.Empty)
        sCondition.Append(string.Format(" AND UserId = '{0}' ", userId));

    if (!string.IsNullOrEmpty(form))
        sCondition.Append(string.Format(" AND FormName = '{0}' ", form));


    string query = string.Format("SELECT * FROM Common.TbHistoryLog {0}", sCondition);
    if (Audits != null)
    {
        Audits.Clear();
        var newItems = oContext.Database.SqlQuery<HistoryLog>(query).ToList();
        if (newItems != null)
            foreach (var newItem in newItems)
                Audits.Add(newItem);
    }
}

Second, this creates a new instance of ClsUserTransactions :

ClsUserTransactions oUserTrans = new ClsUserTransactions())

You need to add items to the one that the DataGrid is bound to and you certainly shouldn't dispose the instance immediately after you have populated its Audits collection...:

private void BtnSearch(object sender, RoutedEventArgs e)
{
    var userId = ((TbUsers)cmbUsers.SelectedItem)?.UserId;
    var from = dtFromDate.Value;
    var to = dtToDate.Value;
    var form = ((BlCommon.TbObjects)cmbForms.SelectedItem)?.ObjectRealName;
    ClsUserTransactions oUserTrans = gvHistory.DataContext as ClsUserTransactions;
    oUserTrans.GetAudits(userId, from, to, form);
}

your ViewModel should implement the INotifyPropertyChanged interface, then notify the property change on the Audits setter:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
...

-

public ObservableCollection<HistoryLog> Audits
{
    get
    {
        return audits;
    }
    set
    {
        audits = value;
        OnPropertyChanged("Audits");
    }
}
ObservableCollection<HistoryLog> audits;

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