[英]Update itemssource in binding to combobox using MVVM pattern in WPF
我正在使用MVVM模式開發WPF應用程序,在該應用程序中我有兩個組合框,我從viewmodel的屬性綁定組合框的itemssource,這些屬性是實現ICollectionView接口的CollectionView類類型。 用於跟蹤當前選定的項目。 因為我需要根據第一個組合框中所選項目的值來更新第二個組合框項目。 這是來自viewmodel類代碼的快照:
public ICollectionView Projects { get; set; }
public ICollectionView Tasks { get; set; }
public ICollectionView Users { get; set; }
public NewTaskViewModel()
{
Projects = new CollectionView(this.GetProjects());
Projects.CurrentChanged += new EventHandler(projects_CurrentChanged);
Users = new CollectionView(this.GetProjectAssignedUsers());
}
void projects_CurrentChanged(object sender, EventArgs e)
{
Api.Project project = Projects.CurrentItem as Api.Project;
this.SelectedProjectId = project.Id;
this.Tasks = new CollectionView(this.GetTaskLists());
}
這是XAML部分:
<ComboBox x:Name="textBox3" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Projects, Mode=TwoWay}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True">
</ComboBox>
<ComboBox x:Name="textBox4" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Tasks}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True">
</ComboBox>
我做錯了什么,因為當我更改當前所選項目時,我沒有更新第二個組合。 希望能有所幫助。 干杯。
您需要實施屬性更改通知。 更改項目后,您將為Tasks
分配一個新的CollectionView
。 為了讓UI知道它,您應該引發PropertyChanged
事件。
public class MyClass : INotifyPropertyChanged
{
private ICollectionView tasks;
public ICollectionView Tasks
{
get
{
return tasks;
}
set
{
tasks = value;
OnPropertyChanged("Tasks");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
請參閱此鏈接以獲取更多詳細信息-https://msdn.microsoft.com/zh-cn/library/ms743695(v=vs.110).aspx
您需要在ViewModel類上實現INotifyPropertyChanged
接口,如下所示:
public class NewTaskViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public ICollectionView Projects { get; set; }
private ICollectionView _Tasks;
public ICollectionView Tasks
{
get {return _Tasks;}
set
{
if(_Tasks != value)
{
_Tasks = value;
OnPropertyChanged("Tasks");
}
}
}
public ICollectionView Users { get; set; }
public NewTaskViewModel()
{
Projects = new CollectionView(this.GetProjects());
Projects.CurrentChanged += new EventHandler(projects_CurrentChanged);
Users = new CollectionView(this.GetProjectAssignedUsers());
}
void projects_CurrentChanged(object sender, EventArgs e)
{
Api.Project project = Projects.CurrentItem as Api.Project;
this.SelectedProjectId = project.Id;
this.Tasks = new CollectionView(this.GetTaskLists());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.