[No0000C2]WPF 数据绑定的调试

WPF的数据绑定是WPF的重要特性之一,但是数据绑定的决议发生在运行时,并且不会抛出异常,所以在数据显示和期望值不同时很难查找原因。
主要有两种方式查找错误:
1DataBinding的表达式无效时,跟踪Debug的输出信息来查找原因
2DataBinding的表达式有效,但是数据和期望值不同,此时可以在Converter中断点调试

方法1:在VS输出窗口跟踪信息

 

<Window x:Class="DebugDataBinding.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <StackPanel x:Name="stack">
        <TextBlock Text="{Binding ElementName=stack, Path=InvalidPath}" />
    </StackPanel>
</Window>

 

此时输出窗口内会有如下信息

System.Windows.Data Error: 39 : 
BindingExpression path error: 'InvalidPath' property not found on 'object' ''StackPanel' (Name='stack')'.
BindingExpression:Path=InvalidPath;
DataItem='StackPanel' (Name='stack');
target element is 'TextBlock' (Name='');
target property is 'Text' (type 'String')

此时分析上面的错误信息可以发现一些错误的原因

方法2:在binding中修改关于绑定信息输出的级别

这种方式可以分别调试每一个binding,输出窗口打印出详细的binding过程,不论成功还是失败。下面(1)和(2)中二选一即可

1)在XAML文件中使用

 

<Window x:Class="DebugDataBinding.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase">
    <StackPanel x:Name="stack">
        <TextBlock Text="{Binding ElementName=stack, Path=InvalidPath, 
                          diag:PresentationTraceSources.TraceLevel=High}" />
    </StackPanel>
</Window>

 

2)在代码中使用

PresentationTraceSources.DataBindingSource.Listeners.Add( new ConsoleTraceListener());
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.All;

方法3:在Converter中断点调试

xaml文件:

<Window x:Class="DebugDataBinding.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:DebugDataBinding" 
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:DatabindingDebugConverter x:Key="debugConverter" />
    </Window.Resources>
    <StackPanel x:Name="stack">
        <TextBlock Text="{Binding ElementName=stack, Path=ActualWidth, 
                          Converter={StaticResource debugConverter}}" />
    </StackPanel>
</Window>

cs文件:

/// <summary>
/// This converter does nothing except breaking the
/// debugger into the convert method
/// </summary>
public class DatabindingDebugConverter : 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;
    }
}
原文地址:https://www.cnblogs.com/Chary/p/No0000C2.html