C# 我可以绑定到DataGrid';是否在不更新支持变量/属性的情况下选择EdItem?
所以,我有一个数据网格,它显示了一个付款列表C# 我可以绑定到DataGrid';是否在不更新支持变量/属性的情况下选择EdItem?,c#,wpf,binding,datagrid,C#,Wpf,Binding,Datagrid,所以,我有一个数据网格,它显示了一个付款列表 <DataGrid x:Name="dataGrid" ItemsSource="{Binding Payments}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="PaymentDate" Binding="{Binding PaymentDate, StringFormat=\{0:d\
<DataGrid x:Name="dataGrid" ItemsSource="{Binding Payments}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="PaymentDate" Binding="{Binding PaymentDate, StringFormat=\{0:d\}}" />
<DataGridTextColumn Header="Amount" Binding="{Binding Amount, StringFormat=\{0:N\}}" />
<DataGridTextColumn Header="Comment" Binding="{Binding Comment}" />
<DataGridTextColumn Binding="{Binding EventCode}" Header="Event Code"/>
<DataGridTextColumn Binding="{Binding DueDate, StringFormat=\{0:d\}}" Header="DueDate"/>
</DataGrid.Columns>
</DataGrid>
我还有第二个数据网格,它应该显示所选付款的预订对象列表
<DataGrid ItemsSource="{Binding SelectedItem.Bookings, ElementName=dataGrid}" AutoGenerateColumns="True" />
我所期望的是,每当我在DataGrid 1中选择一个付款项目时,DataGrid 2都会填充有关如何分配该付款的详细信息。然而,我得到的是一个空的细节数据网格
我知道我可以将SelectedItem属性绑定到ViewModel中的某个属性,并在每次更改该属性时通知我的视图,但看起来DataGrid 2应该知道DataGrid 1的SelectedItem属性已自动更改。我问得太多了,还是我做错了?在WPF中,有三种常见的方法来管理从列表中选择的父子关系
<DataGrid ItemsSource="{Binding Payments/Bookings}" AutoGenerateColumns="True" />
注意,我删除了ElementName引用,这是错误的;您正在绑定到DataContext,而不是父网格上的属性。请确保Bookings的属性是公共属性 您可能还希望在SelectedItem绑定中使用UpdateSourceTrigger=PropertyChanged,如下所示:
ItemsSource="{Binding SelectedItem.Bookings, ElementName=dataGrid, UpdateSourceTrigger=PropertyChanged}"
如果这没有帮助,请尝试使用Snoop来确保数据确实在预订中-如果是,并且没有显示,请在VM中使用属性并在数据类中实现InotifyPropertyChanged,或者通过datagrid1的SelectionChanged EventHandler更新datagrid2的属性,但问题在于细节。尝试此操作并查看在运行时在VS输出窗格中看到的内容,当您更改主网格中的选择时:
ItemsSource=“{Binding SelectedItem.Bookings,ElementName=dataGrid,presentationontracesources.TraceLevel=High}”
是否仔细检查SelectedItem的预订列表是否为空?如果两个数据网格位于同一命名范围内,则无法看到给定代码的错误。请确保所选付款的Bookings集合已填充。您可以尝试使用x:Reference来代替ElmentName,我真是个笨蛋。我没有公开我的预订。谢谢你们的眼睛,伙计们。我以前从未使用过PresentationTraceSources.TraceLevel=High。感谢您的新工具。为什么直接绑定到主数据网格的SelectedItem是错误的?使用的单词是错误的。更好的说法应该是“坏习惯”。如果重命名源控件或尝试在任何其他上下文中使用子控件,则绑定到其他控件上的属性将中断。此外,您现在还依赖于源代码管理的实现,它可以在SelectedItem属性刷新时触发任意次数。最重要的是,绑定到属性元素更难进行单元测试,这就是问题所在。My Bookings属性未设置为public。由于向绑定添加UpdateSourceTrigger=PropertyChanged
的荒谬建议,已撤回upvote。如果你建议这样做,你一定不知道这意味着什么;很明显,这是不可行的。如果你不知道它有什么作用,不要自信地宣称它对人们的束缚有任何神奇的疗效。
<DataGrid ItemsSource="{Binding Payments/Bookings}" AutoGenerateColumns="True" />
ItemsSource="{Binding SelectedItem.Bookings, ElementName=dataGrid, UpdateSourceTrigger=PropertyChanged}"