我试图显示用户制作的操作,将存储到Observable集合并使用ListView显示。我的问题是,Observable集合只有在触发事件或命令时才会更新。如果我只是简单地调用AddItemsToList()方法使用wcf服务回调,那么它不工作。我在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();
问题就在这里:
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;
}
既然你在使用单例,你也需要在视图绑定中使用那个单例。现在,您正在向不同的VM实例添加项目,而不是您正在显示的VM实例。
边注:
从wcf回调方法中调用AddItemsToList()方法
任何时候向ObservableCollection<T>
添加项目,都需要在主(UI)线程上执行。我怀疑你的WCF回调发生在线程池线程上,这可能会阻止一些INotifyCollectionChanged
机制正常工作。