繁体   English   中英

在没有 DependencyProperty 失败的情况下无法从 db 填充集合

[英]Can't populate collection from db without DependencyProperty failure

我坚持了 3 天,将我的数据库中的集合作为属性绑定到 WPF 中的数据网格,尽管我之前做过。 简而言之,我有一个带有 DependencyProperty“CurrentRecord”的视图模型,用于保存要在此视图模型实例中使用的记录的数据库记录号。 它是在用另一个 class 初始化的时候设置的:

内部 void load_Record(记录 selected_record)
{ RecordViewModel vm = new RecordViewModel();
vm.CurrentRecord = selected_record;
RecordBase 记录库 = 新 RecordBase(); //用户控件=视图
记录库.DataContext = vm; ....}

这里一切正常。

我的 ViewModel 属性:

public int record_id
{
    get { return CurrentRecord.record_id; }
}

private ObservableCollection<procedure_record> procedures;
public ObservableCollection<procedure_record> Procedures
{
    get { return procedures; }
    set { procedures = value; }
}
public ICollectionView Procedures_collection { get; set; }

和构造函数

public RecordViewModel()
{
    UserControl_Loaded();
    procedures = new ObservableCollection<procedure_record>();
    Procedures_collection = CollectionViewSource.GetDefaultView(Procedures);
    Procedures_collection.SortDescriptions.Add(new SortDescription("initiation_date", 
        ListSortDirection.Ascending));
}

仍然运作良好。 应用程序可以在文本块中显示 record_id。 但是,如果我尝试填充集合,它会崩溃:

if (procedures == null)
{
    using (var db = new MainEntityModel())
    {
        var query = from pm in db.procedure_record
                    where pm.record_id == this.record_id
                    select pm;

        foreach (var p in query)
        {
            procedures.Add((procedure_record)p);
        }
    }
}  

我尝试将此代码放入构造函数中(或作为单独的 class 方法调用),但 DependencyProperty 出现错误? (为什么?)它是@System:NullReferenceException。 “对象引用未设置为 object 的实例。” 在行获取 { 返回 CurrentRecord;record_id。 } - CurrentRecord.get 返回 null。 找不到此事件之间的联系。 也无法填充集合在 XAML dataGrid 中显示数据:XAML:

<DataGrid ItemsSource="{Binding Procedures_collection}" .../>

寻求您的帮助!

更新

public static readonly DependencyProperty CurrentRecordProperty = 
    DependencyProperty.Register("CurrentRecord", 
        typeof(records), 
        typeof(RecordViewModel));

public records CurrentRecord
{
    get
    {
        return (records)GetValue(CurrentRecordProperty);
    }
    set
    {
        SetValue(CurrentRecordProperty, value);
    }
}

public int record_id
{
    get { return CurrentRecord.record_id; }
}

尝试这个

 var query = (from pm in db.procedure_record
                            where pm.record_id == record_id
                            select pm).ToList();  

 
if( query !=null) Procedures = new ObservableCollection<procedure_record>(query);            

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM