debugging 如何找到Source,它为wpf中的绑定提供数据

mepcadol  于 2023-05-07  发布在  其他
关注(0)|答案(2)|浏览(111)
  • 我是WPF的初学者。在调试使用MVVM模式构建的大型项目时,如何找到为当前绑定元素提供数据的source
  • 比如说
<DataTemplate x:Key="TMPL_NameColumnB">
                <ComboBox VerticalAlignment="Center"
                          Validation.ErrorTemplate="{x:Null}"
                          Panel.ZIndex="1"
                          DisplayMemberPath="Title"
                          ItemsSource="{Binding TypeChoices}"
                          SelectedItem="{Binding TypeChoice}"
                          Visibility="{Binding DataContext.CanChangeType,
                          Converter={StaticResource {x:Type BooleanToVisibilityConverter}},
                          RelativeSource={RelativeSource AncestorType=ListView}}" />
  • 对于上面的数据模板,我如何才能找到,哪个对象TypeChoices,属性用于绑定。
  • 这个问题是为了了解如何在调试时找到数据绑定的源。
5lhxktic

5lhxktic1#

  • 在Visual Studio中选中工具-〉选项-〉XAML热重载下的Enable in-app toolbar选项
  • 使用Debug-〉StartDebugging选项启动应用程序
  • 运行应用程序时,单击应用程序内工具栏上的Go to Live Visual Tree按钮
  • 单击Select Element按钮选择要应用模板的元素
  • 在Visual Studio中,当应用程序仍在运行时,右键单击可视化树中的选定元素,然后选择Show Properties
  • 查看Live Property ExplorerDataContext属性的值。它显示元素的当前DataContext。此类型应该有一个名为TypeChoices的公共属性,以便绑定工作。

有关如何在调试时检查XAML属性的详细信息,请参阅docs

neskvpey

neskvpey2#

1.您必须检查感兴趣的元素的DataContext
例如,如果要检查ComboBox.ItemsSource数据绑定的源:

**a)**首先检查绑定表达式。在这种情况下,它将使用隐式的源符号{Binding PropertyPath},该符号始终指向本地/继承的DataContext作为源(但它也可以显式地设置属性RelativeSourceElementNameSource,这将沿着可视化树更改源)。本地DataContext是定义绑定的元素的DataContextComboBox.DataContext
**B)**使用可视化树检查器查找ComboBox并检查DataContext属性。

如果绑定已经定义了RelativeSourceElementName属性,那么您将查找相应的元素并检查其DataContext
Inspect XAML properties while debugging
How to: Use the WPF Tree Visualizer
Introducing the UI debugging tools for XAML
1.或者,使调试器跟踪程序能够输出绑定信息。如果数据绑定的跟踪级别设置为例如InformationVerbose,您应该通过检查“输出”窗口中的跟踪输出来找到特定绑定的数据源。
How to: Display WPF Trace Information
要更改特定绑定的跟踪级别,可以设置PresentationTraceSources.TraceLevel attached属性。
只需将其附加到Binding对象:

<!-- Note: you would have to define a `xmlns` import 
     and qualify the attached property using the alias. -->
<ComboBox xmlns:systemDiag="clr-namespace:System.Diagnostics;assembly=WindowsBase" 
          ItemsSource="{Binding Items, systemDiag:PresentationTraceSources.TraceLevel=High}" />

1.如果感兴趣的绑定产生错误,您始终可以打开Visual Studio“XAML Binding Failures”工具窗口并从那里检查绑定。
参见XAML data binding diagnostics

相关问题