[WPF]如何调试Data Binding
前言
在WPF开发中,将ViewModel中对象绑定到UI上时,会出现明明已经将数据对象Binding到UI,但是UI上就是不显示等等的问题。这篇博客将介绍WPF Data Binding调试相关的内容。
场景一(Binding的属性不存在)
ViewModel:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel() { Id = , Name = "Tom", Age = };
}
} public class ViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
XAML:
<StackPanel Margin="10">
<TextBlock Text="{Binding ID}" />
<TextBlock Text="{Binding Name}" Margin="0,10" />
<TextBlock Text="{Binding Age}" />
</StackPanel>
运行结果:

UI中Binding的ID值没有显示出来。请注意加粗的代码,在UI代码中,由于拼写错误,将Id写成了ID。但是这段代码在编译时不会报错,在VS Output窗口中也不会有提示/警告信息。在程序运行时,仔细查看VS Output窗口,此时会有如下信息 (对信息进行了精简)
System.Windows.Data Error: 40 : BindingExpression path error: 'ID' property not found on 'object' ''ViewModel' (HashCode=20915929)'. BindingExpression:Path=ID; DataItem='ViewModel' (HashCode=20915929); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
这段信息告诉提示说在ViewModel对象上没有找到ID属性,此时我们再去检查一下ViewModel发现,原来是将Id错误的写成了ID。一般这种错误的提示开头为:System.Windows.Data Error:
场景二(使用System.Diagnostics来追踪)
XAML:
<Window x:Class="WpfBindingDebug.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock Text="{Binding Title}" />
</StackPanel>
</Window>
将Title属性Binding到TextBlock的Text属性上面,XAML和C#代码中均未指定DataContext属性。编译项目并运行程序,在VS Output中没有任何提示/警告信息。此时应该如何调试呢?可以通过设置PresentationTraceSources对象的TraceLevel来强制WPF输出所有的Binding方面的信息。
更多PresentationTraceSources信息可以参考:
对XAML代码进行如下修改(注意加粗的代码行):
<Window x:Class="WpfBindingDebug.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock Text="{Binding Title, diag:PresentationTraceSources.TraceLevel=High}" />
</StackPanel>
</Window>
编译并运行程序,在VS Output窗口中可以找到关于Binding的信息(对信息进行了精简):
System.Windows.Data Warning: 56 : Created BindingExpression (hash=39201736) for Binding (hash=44325851)
System.Windows.Data Warning: 58 : Path: 'Title'
System.Windows.Data Warning: 60 : BindingExpression (hash=39201736): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=39201736): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=39201736): Attach to System.Windows.Controls.TextBlock.Text (hash=17911681)
System.Windows.Data Warning: 67 : BindingExpression (hash=39201736): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=39201736): Found data context element: TextBlock (hash=17911681) (OK)
....
System.Windows.Data Warning: 67 : BindingExpression (hash=39201736): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=39201736): Found data context element: TextBlock (hash=17911681) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=39201736): DataContext is null
System.Windows.Data Warning: 67 : BindingExpression (hash=39201736): Resolving source (last chance)
System.Windows.Data Warning: 70 : BindingExpression (hash=39201736): Found data context element: TextBlock (hash=17911681) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=39201736): Activate with root item <null>
System.Windows.Data Warning: 106 : BindingExpression (hash=39201736): Item at level 0 is null - no accessor
System.Windows.Data Warning: 80 : BindingExpression (hash=39201736): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 88 : BindingExpression (hash=39201736): TransferValue - using fallback/default value ''
System.Windows.Data Warning: 89 : BindingExpression (hash=39201736): TransferValue - using final value ''
注意:在Visual Studio 2010中需要进行如下设置才能看到上面的提示信息:因为VS 2010默认将下面的设为Off。
Tools -> Options -> Debugging -> Output Window -> WPF Trace Settings -> Data Binding -> set to Warning

程序一直在尝试寻找Visual Tree上的可以Binding的Title值,最终找到一个合适的,DependencyProperty.UnsetValue。
上述方法对查找单个页面Binding很有用,当然我们也可以全局的来收集这些Binding信息。在App.xaml.cs中添加:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
PresentationTraceSources.Refresh();
PresentationTraceSources.DataBindingSource.Listeners.Add(new ConsoleTraceListener());
PresentationTraceSources.DataBindingSource.Listeners.Add(new DebugTraceListener());
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Warning | SourceLevels.Error;
base.OnStartup(e);
}
} public class DebugTraceListener : TraceListener
{
public override void Write(string message)
{
// Write your log here.
} public override void WriteLine(string message)
{
// Write your log here.
}
}
场景三(使用ValueConverter来调试)
场景一和场景二中的方法解决因拼写错误或者无明确DataContext时非常有效。不过有时候真正的通过VS进行调试一下,更加直观,便捷。可以使用实现一个简单的调试使用的Converter,然后将其Binding到目标上,
public class DebugConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Debugger.Break();
return value;
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
Debugger.Break();
return value;
}
}
Debugger.Break()的效果和VS中F9设置断点是一样的。
XAML
<Window x:Class="WpfBindingDebug.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfBindingDebug"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:DebugConverter x:Key="DebugConverter" />
</Window.Resources>
<StackPanel>
<TextBlock Text="{Binding Id, Converter={StaticResource DebugConverter}}" />
</StackPanel>
</Window>
感谢您的阅读~如果您有其他关于Data Binding的调试方式,欢迎在评论区指出~
[WPF]如何调试Data Binding的更多相关文章
- WPF中的Data Binding调试指南
大家平时做WPF开发,相信用Visual studio的小伙伴比较多.XAML里面曾经在某些特殊版本的Visual Studio中是可以加断点进行调试的,不过目前多数版本都不支持在XAML加断点来调试 ...
- WPF之数据绑定Data Binding
一般情况下,应用程序会有三层结构:数据存储层,数据处理层(业务逻辑层),数据展示层(UI界面). WPF是“数据驱动UI”. Binding实现(通过纯C#代码) Binding分为source和ta ...
- WPF QuickStart系列之数据绑定(Data Binding)
这篇博客将展示WPF DataBinding的内容. 首先看一下WPF Data Binding的概览, Binding Source可以是任意的CLR对象,或者XML文件等,Binding Targ ...
- .NET: WPF Data Binding
WPF是分离UI和Logic的最佳工具,不同于Window Form的事件驱动原理,WPF采用的是数据驱动,让UI成为了Logic的附属,达到分离的效果. 本篇主要讲讲wpf的精华:data bind ...
- Data Binding in WPF
http://msdn.microsoft.com/en-us/magazine/cc163299.aspx#S1 Data Binding in WPF John Papa Code downl ...
- WPF binding<一> Data Binding在WPF中的地位
在代码中看到 <Image Source="{Binding ElementName=LBoxImages, Path=SelectedItem.Source}" /> ...
- WPF教程三:学习Data Binding把思想由事件驱动转变为数据驱动
之前大家写代码都喜欢用事件驱动,比如说鼠标输入的click事件.初始化的内容全部放在窗体加载完毕的load事件,等等,里面包含了大量的由事件触发后的业务处理代码.导致了UI和业务逻辑高度耦合在一个地方 ...
- WPF中的数据绑定Data Binding使用小结
完整的数据绑定的语法说明可以在这里查看: http://www.nbdtech.com/Free/WpfBinding.pdf MSDN资料: Data Binding: Part 1 http:// ...
- Data Binding和INotifyPropertyChanged是如何协调工作的?
前言 WPF的一大基础就是Data Binding.在基于MVVM架构的基础上,只有通过实现INotifyPropertyChanged接口的ViewModel才能够用于Data Binding. 要 ...
随机推荐
- 浅谈lvs和nginx的一些优点和缺点
借鉴一些网上资料整理了简单的比较: LVS的负载能力强,因为其工作方式逻辑非常简单,仅进行请求分发,而且工作在网络的第4层,没有流量,所以其效率不需要有过多的忧虑. LVS基本能支持所有应用,因为工作 ...
- [补档] 大假期集训Part.1
新博客搭起来先补一发档... 那就从大假期集训第一部分说起好了QwQ 自己还是太菜掉回了2016级水平 day1: day1的时候来得有点晚(毕竟准高一)然后进机房发现早就开考了还没有给我题面于是搞了 ...
- 完整版ajax+百度echarts实现统计图表demo并随着窗口大小改变而自适应
1.前言 百度Echarts会常用到我们的项目中做统计,api很详细,demo也非常之多,我们常用的是应有尽有了,做一些小项目的时候,百度echarts的demo已足够用了.今天呢.主要是跟小白讲一下 ...
- Android与NativeC传递数据不正确问题
操作系统:Windows8.1 显卡:Nivida GTX965M 开发工具:Android studio 2.3.3 这两天一直在调试一个BUG,具体为通过 NativeC 来处理上层Android ...
- java中的各种数据类型在内存中存储的方式
原文地址:http://blog.csdn.net/aaa1117a8w5s6d/article/details/8251456 1.Java是如何管理内存的 java的内存管理就是对象的分配和释放问 ...
- dotnet core部署方式两则:CLI、IIS
最近在使用dotnet core研究整个开发过程,使用下面两种方式部署: 一,使用 dotnet run 命令运行 在项目路径,shift+右键,选择 “在此处打开命令窗口”,在CMD窗口中运行“do ...
- 案例:Oracle报错ASM磁盘组不存在或没有mount
案例:Oracle报错ASM磁盘组不存在或没有mount 环境:RHEL 6.5 + Oracle Standby RAC 11.2.0.4 我做Standby RAC实验时,在恢复控制文件时,报错无 ...
- C#使用Xamarin开发可移植移动应用目录
Xamarin.Android系列 C#开发移动应用系列(1.环境搭建) C#开发移动应用系列(2.使用WebView搭建WebApp应用) C#开发移动应用系列(3.使用照相机扫描二维码+各种基础知 ...
- 最新 Zookeeper + Flume + Kafka 简易整合教程
在大数据领域有很多耳熟能详的框架,今天要介绍的就是 zookeeper.flume.kafka.因为平时是做数据接入的,所以对这些实时的数据处理系统不是很熟悉.通过官网的简要介绍,搭建了一套简要的平台 ...
- 使用yeoman构建angular应用
本文将介绍如何亲手来完成一个yeoman的generator,以实现快速构建最适合自己的项目. 本文将实现的generator起名为ngtimo,依照yeoman的命名规矩就叫做generator-n ...