简体   繁体   English

DataGrid未绑定到ObservableCollection

[英]DataGrid is not bound to the ObservableCollection

I have a button in my view that execute this method in the ViewModel: 我的视图中有一个按钮,可以在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: Audits属性:

 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不会使用Audits集合进行更新:

<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 ?: 您为什么不简单地清除并重新填充相同的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 实例

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...: 您需要向DataGrid绑定的对象添加项目,并且在填充其Audits集合之后,您当然不应该立即处置该实例...:

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: 您的ViewModel应该实现INotifyPropertyChanged接口,然后在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 绑定了ObservableCollection的dataGrid中的计算列 - Calculated column in a dataGrid bound with a ObservableCollection 在 MVVM 中对绑定到 DataGrid 的 ObservableCollection 进行排序 - Sort ObservableCollection bound to DataGrid in MVVM 访问绑定到 WPF DataGrid 的 ObservableCollection 中的项目 - Accessing items in ObservableCollection bound to WPF DataGrid 访问ObservableCollection中的项目绑定到WPF DataGrid - Accesing items in ObservableCollection bound to WPF DataGrid WPF将项添加到绑定到observablecollection异常的datagrid - WPF add item to datagrid bound to observablecollection exception 绑定到datagrid的ObservableCollection - 使用工厂方法 - ObservableCollection bound to datagrid - Utilizing a factory method 从绑定到数据网格Silverlight的observablecollection中删除项目? - Removing items from a observablecollection bound to a datagrid Silverlight? 删除绑定到 ObservableCollection 的 DataGrid 中的选定行 - Delete selected row in DataGrid bound to an ObservableCollection 在 ViewModel 中修改 ObservableCollection 时绑定到 ObservableCollection 的 DataGrid MultiSelect 不稳定 - DataGrid MultiSelect bound to ObservableCollection unstable when ObservableCollection is modified in the ViewModel 问:C#WPF数据网格绑定到ObservableCollection <T> 没有更新 - Q: C# WPF DataGrid bound to ObservableCollection<T> gets not updated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM