gpt4 book ai didi

c# - 在 ViewModel 中使用 Observable 集合创建 DependencyPropery

转载 作者:太空宇宙 更新时间:2023-11-03 21:14:29 25 4
gpt4 key购买 nike

<分区>

我有 WPF 应用程序,我正在使用 MVVM。我有一个名为 Session 的类,如下所示: session .cs

 public class Session:ObservableCollection<Session>
{
public int value { get; set; }
public string name { get; set; }



}

public class CustomSession:DependencyObject
{
public static readonly DependencyProperty SessionCollectionProperty =
DependencyProperty.Register("SessionCollection", typeof(Session), typeof(CustomSession), new PropertyMetadata());

public Session SessionCollection
{
get { return (Session)GetValue(SessionCollectionProperty); }
set { SetValue(SessionCollectionProperty, value); }
}


}

我的 ViewModel 如下: View 模型.cs

 public class ViewModel:BindableBase
{
private ObservableCollection<Session> _sessions;
public ObservableCollection<Session> sessionsCollection
{
get { return _sessions; }
set { SetProperty(ref _sessions, value); }
}

public ViewModel()
{
sessionsCollection = allSessions();
}

public ObservableCollection<Session> allSessions()
{
CustomSession custom = new CustomSession();
custom.SessionCollection.Add(new Session() { name = "LocateSession", value = 10 }); //System.Null Reference Exception.
custom.SessionCollection.Add(new Session() { name = "TrackSession", value = 20 });
custom.SessionCollection.Add(new Session() { name = "MonitorSession", value = 25 });
custom.SessionCollection.Add(new Session() { name = "MassSnapshot", value = 18 });
custom.SessionCollection.Add(new Session() { name = "MassContinuous", value = 9 });
return custom.SessionCollection;
}
}

我有一个 UI,我想在其中绑定(bind)这个 Observable 集合。每当我尝试添加一个项目时custom.SessionCollection.Add(new Session() { name = "LocateSession", value = 10 });我得到空引用异常。我想从 ViewModel 填充 ObservableCollection。我该怎么做。请帮忙。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com