Debug Databinding Issues in WPF, databindingwpf

Source: Internet
Author: User

Debug Databinding Issues in WPF, databindingwpf

DataBinding is one of the most powerful features in WPF. but because it resolves the bindings at runtime and does not throw limits tions, it's sometimes hard to find the reason why the data do not appear as expected. there are mainly two reasons:

  • The DataBindingExpression is invalid. Then useTrace OutputTo resolve.
  • The DataBinding expression is valid,The result is not the expected. Then useDebug ConverterTo resolve it.
Method 1: Trace messages in the output window

In the example, the text property of the TextBlock is bound to the property "InvalidPath" of the StackPanel-which does not exists.

<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>

 

In this case the invalid databinding expression is reported by a trace message in the output 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')

Note:Binding to a path of a property that has NULL value isValid expressionAnd does not generate an error message (for e.g. binding to a property of the data context that is NULL ).

Adjust the trace level (. NET 3.5 and higher)

NET3.5 has a new feature that allows you to set the level of details of trace messagesNone,Low,MediumOrHigh.

To set the trace level you have to include an extra namespace to your 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>

 

The following snipped shows how to adjust the trace level by code:

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

Method 2: Use a ValueConverter to break into the debugger

A simple trick is to write a value converter that does nothins should t breaking into the debugger. all you need to do now is to add this converter to the binding expression that fails and you can easily see the values that shoshould be bound.

 
/// <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;    }}

 

To use the converter in XAML, reference the namespace of the assembly that contains the converter and add an instance of it to the resources of your window.

 
<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>

 

Link to the original article above

 

There are also some optional configuration files:

<Configuration> <system. diagnostics> <sources> <! -- <Source name = "System. windows. data "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> <! -- <Source name = "System. windows. dependencyProperty "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> <! -- <Source name = "System. windows. freezable "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> <! -- <Source name = "System. windows. routedEvent "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> <! -- <Source name = "System. windows. media. animation "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> <! -- <Source name = "System. windows. nameScope "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> <! -- <Source name = "System. windows. resourceDictionary "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> <! -- <Source name = "System. windows. markup "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> <! -- <Source name = "System. windows. documents "switchName =" SourceSwitch "> <listeners> <add name =" textListener "/> </listeners> </source> --> </sources> <switches> <add name = "SourceSwitch" value = "Off"/> <! -- <Add name = "SourceSwitch" value = "All"/> --> <! -- <Add name = "SourceSwitch" value = "Verbose"/> --> <! -- <Add name = "SourceSwitch" value = "Warning"/> --> <! -- <Add name = "SourceSwitch" value = "Activity"/> --> </switches> <sharedListeners> <! -- This listener sends output to the console --> <add name = "console" type = "System. Diagnostics. leletracelistener" initializeData = "false"/> <! -- This listener sends output to an Xml file named AvTrace. xml --> <! -- <Add name = "xmlListener" type = "System. Diagnostics. XmlWriterTraceListener" traceOutputOptions = "None" initializeData = "AvTrace. xml"/> --> <! -- This listener sends output to a file named AvTrace.txt --> <! -- <Add name = "textListener" type = "System. diagnostics. textWriterTraceListener "initializeData =" AvTrace.txt "/> --> </sharedListeners> <trace autoflush =" true "indentsize =" 4 "> </trace> </system. diagnostics> </configuration>Optional configuration items of App. Config

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.