[英]WPF Data Binding with multiple controls
在WPF中,我试图绑定多个控件,但是当第一个控件更改时,第二个控件没有更改。
我有两个类:Task类和Log类,它们作为一个集合存储在Task类中。 下面的列表框绑定到任务以及所选任务的内部日志。
问题在于,列表框在第一次加载时就可以很好地填充,但是如果我选择其他任务,我希望日志将更新为新任务的集合,但与原始任务相比不会发生变化首次加载时选择的任务。 我想念什么?
在设计器中:
<ListBox x:Name="listBoxTasks" ItemsSource="{Binding}" DisplayMemberPath="Key"
Grid.Row="0" Grid.Column="0" Grid.RowSpan="2">
</ListBox>
<ListBox x:Name="listBoxLogs"
ItemsSource="{Binding Logs}" DisplayMemberPath="EntryDate"
Grid.Row="1" Grid.Column="1">
</ListBox>
在后面的代码中:
public MainWindow()
{
InitializeComponent();
IMongoCollection<Task> tasks = DataManager.GetData();
this.DataContext = tasks.AsQueryable();
}
Task类:
public class Task : BusinessBase<Task>
{
public ObjectId _Id { get; set; }
public string Key { get; set; }
public string Description { get; set; }
public string Summary { get; set; }
public string Details { get; set; }
public IEnumerable<Log> Logs { get; set; }
public IEnumerable<Link> Links { get; set; }
public IEnumerable<String> RelatedKeys { get; set; }
public IEnumerable<TaskItem> Items { get; set; }
}
您的Task
类需要实现INotifyPropertyChanged接口,以便一旦基础数据发生任何变化,它就可以告诉WPF UI某些更改现在可以再次更新/刷新控件。
您的任务类需要实现INotifyPropertyChanged
您必须将第一个ListBox
SelectedItem
绑定到Task
模型的对象,并为SelectionChanged
添加事件处理程序。 在此事件内,您必须通过选定的Task模型填充日志,还必须在类中实现INotifyPropertyChanged
。
在我看来,第二个绑定根本不起作用,因为DataContext
是Tasks
的可枚举对象,而该可枚举对象本身没有称为Logs
属性。 您可以尝试使用IsSynchronizedWithCurrentItem
以及对当前项目的绑定:
<ListBox x:Name="listBoxTasks" ItemsSource="{Binding}" DisplayMemberPath="Key"
Grid.Row="0" Grid.Column="0" Grid.RowSpan="2"
IsSynchronizedWithCurrentItem="True"> <!-- Set this -->
</ListBox>
<ListBox x:Name="listBoxLogs" DisplayMemberPath="EntryDate"
Grid.Row="1" Grid.Column="1"
ItemsSource="{Binding /Logs}"> <!-- Note the slash which indicates a binding to the current item -->
</ListBox>
您还可以绑定到另一个ListBox
的SelectedItem
,但这在控件之间引入了冗余依赖关系。 还要注意,如果更改数据对象中的任何属性,则需要实现其他应答者INotifyPropertyChanged
提到的接口。
我已经全部工作了。 我实现了INotifyPropertyChanged,尽管那不能解决问题。
我现在正在使用MVVM模式。 这有帮助...我正在使用的NoRM库没有SelectionChanged事件。 我创建了一个视图模型,并能够将这些模型转换为ObservableCollections。 现在,我只是在为Task类更改选择时设置Logs控件DataContext。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.