我正在尝试显示将存储到可观察集合中的用户制作的操作,并使用 ListView 进行显示。我的问题是Observable集合只在发生事件或命令时才更新。如果我只是简单地使用wcf服务回调调用AddItemsToList()方法,那么它不起作用..我绑定Datacontext in我的window.xaml.cs构造函数不在xaml中。我的Observable集合存储在我的视图模型中。
我的代码:
AgentWindow.xaml.cs
public AgentWindow()
{
InitializeComponent();
var agentViewModel = new AgentViewModel();
//binding list itemsource to observable collection
lstOperations.ItemsSource = agentViewModel.OperationList;
store view model into data context
this.DataContext = agentViewModel;
}
AgentWindows.xaml
<ListView x:Name="lstOperations">
<ListView.View>
<GridView x:Name="grdOperations">
<GridViewColumn Header="username" DisplayMemberBinding="{Binding Username}"/>
<GridViewColumn Header="function name" DisplayMemberBinding="{Binding FunctionName}"/>
</GridView>
</ListView.View>
</ListView>
AgentViewModel.cs
public class AgentViewModel : INotifyPropertyChanged
{
public ObservableCollection<Operation> OperationList;
public AgentViewModel()
{
Initialize_Commands();
this.OperationList = new ObservableCollection<Operation>();
}
//Method that will be used to store new information into list
public void AddItemsToList()
{
OperationList.Add(new Operation
{
Username = "SomeUsername",
FunctionName = "SomeFunction"
});
}
//Singleton for this class
private static AgentViewModel _instance;
public static AgentViewModel Instance
{
get
{
return _instance ?? (_instance = new AgentViewModel());
}
}
//event that is not used
public event PropertyChangedEventHandler PropertyChanged;
}
从wcf回调方法
调用AddItemsToList()方法 AgentViewModel.Instance.AddItemsToList();
答案 0 :(得分:3)
问题在于:
public AgentWindow()
{
InitializeComponent();
// Don't create a **new** VM
//var agentViewModel = new AgentViewModel();
// Get your main instance
var agentViewModel = AgentViewModel.Instance;
//binding list itemsource to observable collection
lstOperations.ItemsSource = agentViewModel.OperationList;
store view model into data context
this.DataContext = agentViewModel;
}
由于您使用的是单例,因此您还需要在View绑定中使用该单例。现在,您将项目添加到与您正在显示的VM实例不同的VM实例上。
旁注:
从wcf回调方法
调用AddItemsToList()方法
每次向ObservableCollection<T>
添加项目时,都需要在主(UI)线程上执行此操作。我怀疑你的WCF回调是在线程池线程上发生的,这可能会阻止某些INotifyCollectionChanged
机制正常工作。