모아온 글(영어)2012.08.14 11:07

The WPF and Silverlight platforms use late bound data binding resolution for bindings in XAML files. This feature allows a DataContext to be set at run-time and the objects within that DataContext to resolve their property bindings then. This late binding enables cool features like DataTemplates, composable applications and run-time loading of loose XAML.

A side effect of late bound binding resolution that can cause developers some minor frustration is that their controls do not display the expected data at run-time.

This article will explain troubleshooting techniques that can help you locate and correct the problem.

Data Binding Overview

Data binding is fundamental to WPF and Silverlight. You will struggle with your application designs, coding and troubleshooting until you understand data binding in these platforms.

The best data binding resource available is the MSDN Data Binding Overview topic. If you have not read or don't fully understand the material in this topic, please take the required amount of time to learn this material.

Ounce of Prevention is Worth a Pound of Cure

Visual Studio 2010 has great tooling to wire up data bindings and checked them at design-time. Please read this article: How to Enable Using the Binding Builder in WPF and Silverlight Applications.

Visual Studio 2010 has excellent design-time sample data support. If you use design-time sample data, you'll immediately see controls that don't have expected data values at design-time.

For a detailed examination of sample data in the WPF and Silverlight Designer for Visual Studio 2010, please read this article: Sample Data in the WPF and Silverlight Designer.

Troubleshooting List

  • Verify that DataContext is set in either XAML or code
  • Run the application and view the output in the Debug Output Window
    • For WPF applications you can increase or decrease the amount of information displayed in the Debug Output Window by changing the WPF Trace Settings, Data Binding value
  • Name the control that has DataContext assigned, set a break point in the code, and view the named control's DataContext property in the debugger
  • If binding to a CLR object, put a breakpoint in the source property getter to see that its actually being queried
  • Add a converter to a binding, then put a breakpoint in the converter


 

Verify that DataContext is set in either XAML or Code

This tip is along the lines of, "if the TV won't turn on, check that it's plugged in."

This is important for many reasons, but one is easily overlooked; if a DataContext is null, the Debug Output Window will not display any error messages in Silverlight or in WPF.

In WPF you can use the below PresentationTraceSources on a binding and set the TraceLevel to High to view errors related to a null DataContext.

View the Debug Output Window

If you have the DataContext set, any data bindings within that DataContext that can't be resolved will be listed in the Debug Output Window at run-time.

Sample Debug Output Window Data Binding Error

Sample One

System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''Object' (HashCode=62178992)'. BindingExpression:Path=FirstName; DataItem='Object' (HashCode=62178992); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')

Sample Two

System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''Customer' (HashCode=13640894)'. BindingExpression:Path=FirstName; DataItem='Customer' (HashCode=13640894); target element is 'TextBox' (Name=''); target property is 'Tag' (type 'Object')

While the above messages look verbose and complex, you can glean several interesting points of information that will help you correct this data binding:

  • The Binding Path is FirstName. Search your XAML file for FirstName and see if you expect the DataContext to expose a FirstName property whose scope will allow this binding to resolve this property.
  • The Source object in Sample One is of Type Object. There is a good chance the Type Object does not have a FirstName property.
  • The Source object in Sample Two is of Type Customer. Check your Customer Type; does it have a FirstName property?
  • Notice in Sample Two, the target property is Tag. In all likelihood, the Text property was the desired target property and not Tag. Also the Type of Tag is Object; you would probably be expecting String when binding to the FirstName property.

Review

  • Verify the property name is spelled correctly
  • Verify the property name has the correct character casing. FirstName is not the same as firstName.
  • Verify the property is a member of the DataContext Type
  • Verify the target element is the correct Type
  • Verify the target property name and Type are correct



 

Important

Data binding property path names are Case Sensitive.



 

WPF Trace Settings, Data Binding


 

Important

The default value of the WPF Trace Settings, Data Binding is "Error." It is recommended that you change this setting to "Warning." Please read this short blog postfor more information.

This is required if you use the attached property PresentationTraceSources.TraceLevel. If the value is set to "Error" you won't see any of the PresentationTraceSources.TraceLevel warning messages.

To change the WPF Trace Settings, Data Binding value to "Warning," navigate to Tools, Options, Debugging, Output Window, WPF Trace Settings, Data Binding and set the value to Warning as I've done in the below image.

Note

This setting affects all bindings in WPF the application. For a more targeting approach, see the PresentationTraceSources.TraceLevel section below.



 

Important

If this setting is set to, "Off" you will not see any WPF Data Binding Errors in the Debug Output Window.


 

PresentationTraceSources.TraceLevel

Introduced to WPF in .NET 3.5 SP1, the PresentationTraceSources.TraceLevel attached property allows developers to dial up the amount of information outputted in the Debugger Output Window for a binding.

The below XAML snippet shows how to apply the PresentationTraceSources.TraceLevel attached property to a binding. 

<Window 
    xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
    xmlns:local="clr-namespace:DebugDataBindings"
    x:Class="DebugDataBindings.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="layoutRoot">
        <Grid.Resources>
            <local:DebugConverter x:Key="debugConverter" /> 
        </Grid.Resources>
        <TextBox 
            Text="{Binding Path=Customer.FirstName, diag:PresentationTraceSources.TraceLevel=High}"   
            Height="23" HorizontalAlignment="Left" Margin="90,18,0,0" VerticalAlignment="Top" Width="120"/>
    </Grid>
</Window>

Use the Debugger Quick Watch to View the DataContext

If the above suggestions to do not solve your problem:

  • Locate the control's parent panel like a Grid in your XAML
  • Apply a x:Name to the control
  • Set a break point in your code, and view the named panel control's DataContext property in the debugger

Open the QuickWatch dialog, change the Expression to the named control in the XAML and look at the control's DataContext property.

  • In the below image, I have changed the Expression to, "this.layoutRoot.DataContext" in VB.NET you would change it to, , "Me.layoutRoot.DataContext"

This information will at least confirm the shape (Type) of the DataContext and the values inside the DataContext.

This tip provides value in two ways:

  • If the DataContext had been set then subsequently changed by some other code, you'll be expecting the initial value but will see another value
  • If the property was nested within another class, you can easily see the shape of your DataContext and then ensure that your bindings are properly dotted in.
    • Notice the path to the FirstName property is DataContext.Customer.FirstName.
    • This means that if you wanted to data bind to the Text property on a TextBox that was a child of the Grid named layoutRoot, the binding expression must read:

      <TextBox Text="{Binding Path=Customer.FirstName}" ... />

Place a Breakpoint inside the Source Property Getter

If you are binding to a CLR object, put a breakpoint in the source property getter to see that it's actually being queried.

If it's not be queried, you have a mismatch in the property name, property is not properly dotted in, DataContext is null or does not contain this property.

Add a Converter to a binding, then put a Breakpoint in the Converter

Important

The use of a converter to troubleshoot a data binding only works if the DataContext is not null, and the DataContext Type exposes a property with the same name in the binding expression.

A ValueConverter allows you to view the data as its being moved between the target and source. In the below image the converter in the middle is named "ColorBrushConverter."

The below converter is a no-op converter named, "DebugConverter." This reusable converter will allow you to place a breakpoint in the Convert and ConvertBack methods and then view the value of the "value" parameter at debug time. 

using System;
using System.Windows.Data;

namespace DebugDataBindings {
    public class DebugConverter : IValueConverter {

        public Object Convert(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture) {

            //set a breakpoint here
            return value;
        }

        public Object ConvertBack(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture) {

            //set a breakpoint here
            return value;
        }
    }
}

The below XAML show the above converter being applied to the TextBox.Text property binding.

<Grid x:Name="layoutRoot">
        <Grid.Resources>
            <local:DebugConverter x:Key="debugConverter" /> 
        </Grid.Resources>
        <TextBox Text="{Binding Path=Customer.FirstName, Converter={StaticResource debugConverter}}"   
            Height="23" HorizontalAlignment="Left" Margin="90,18,0,0" VerticalAlignment="Top" Width="120"/>
    </Grid>

Comments

Microsoft values your opinion about our products and documentation. In addition to your general feedback it is very helpful to understand:

  • How the above features enable your workflow
  • What is missing from the above features that would be helpful to you

Thank you for your feedback and have a great day,

Karl Shifflett 
Expression Team

Posted by UXPRO
분류없음2009.01.07 10:10
원본 : http://blog.ningzhang.org/2008/12/silverlight-debugging-with-visual.html

소개

Debugging is an important part of software development, so knowledge of debugging tools and techniques are very important for developer productivity and software quality. Even though information about debugging are readily available on MSDN, various blogs and sites, it seems that many, if not most, developers are too busy to dig out those information or get familiar with various tools and techniques, so they miss out big on the productivity and quality gains they could have with those debugging tools and techniques. I thought it may be helpful to pull those information together. It ended up too big for a blog post, so I trimmed it down to be an overview of just Visual Studio and WinDbg (and links to references for more information), and broke it into two posts. I use the following simplest Silverlight application for debugging, so I can focus on debugging tools and techniques, instead of using real world examples that may require too much irrelevant/confidential knowledge or take too much effort to explain.

SilverlightApplication1

SilverlightApplication1

 

Visual Studio 디버그 윈도우

Visual Studio is a power tool and the most convenient for debugging managed applications (both .NET and Silverlight). Its GUI makes common debugging operations like breakpoint, backtracked, data manipulation, execution control etc super easy and straightforward. It is highly recommended that you check Debugging in Visual Studio on MSDN frequently, especially the following sections:

Every time I read those links or any thing else on MSDN, I learn something new.

Visual Studio Debug Windows

Immediate Window

Besides debug windows, if you want to use commands or prefer command line interface (especially those who are more accustomed to native coding and/or low level debugging with tools ntsd or gdb), you can use Immediate and Command windows.

You can examine/change objects and their properties and call methods from Immediate Window, and with the convenience of IntelliSense and tool:

Immediate Window

Immediate window has an subset of ntsd commands, and more importantly, can be used to load SOS (I will discuss SOS with WinDbg in next post). 

Immediate Window Commands

Unfortunately none of above commands works while debugging Silverlight, because Silverlight project settings doesn't have the option to turn on native debugging. If someone knows how to debug Silverlight with SOS and Visual Studio, please let me know.

Immediate Window

This limitation can be mitigated to some extend by using Visual Studio commands. You can either use those commands within Immediate Window with >: 

Visual Studio Commands in Immediate Window

or switch to Command Window from Immediate Window with >cmd:

Immediate Window

Command Window

Command Window provides a command line interface for more than just debugging. It is the CUI of Visual Studio, and with intellisense:

Command Window

Command Window

And you can switch from Command Window to Immediate Window with rimmed command.

Command Window

You can read more about Command Window on MSDN, especially:

Debug With .NET Framework Source Code

It is pretty common that sometimes some API's you use don't work as expected/assumed/documented, so being able to debug the source code of those API's is very helpful in identifying/fixing issues. The biggest API set is .NET framework. Scott Guthrie has a blog post .NET Framework Library Source Code now available earlier this year, and Shawn Burke, my boss, has a post with detailed instruction and FAQ/troubleshooting on Configure Visual Studio to Debug .NET Framework Source Code.

I tried with Silverlight:

Configure Visual Studio to Debug .NET Framework Source Code

but it seems Silverlight source isn't available yet:

No Silverlight Source Code

Before Silverlight source becomes available, you can use the great tool .NET Reflector, originally written by Lutz Redder, now owned by RedGate, to browse Silverlight source code:

.NET Reflector

Conclusion

As we can see, Visual Studio is the best tool for debugging managed applications, and it has lots of advanced features that may not be very well known, like the commands in Immediate and Command windows. Not all features are available for Silverlight debugging, particularly SOS and Silverlight source code. I hope SOS be part of Visual Studio, and all NTSD (and most extension) commands available in Visual Studio.

Posted by UXPRO

RIA, UX, WPF, Silverlight ...

IT 분야는 지치지도 않고 새로운 정보들을 쏟아 내고 있습니다.

그 중에서 제가 관심이 가는 제품은 Microsoft에서 작년 이맘때쯤 출시한 Expresion Blend입니다.

옛말에 "사공이 많으면 배가 산으로 간다"는데 Expresion Blend는  그 사공들이 형제들이라 더 혼란스럽습니다. ^^

그러나 모두가 '엄친아, 엄친딸'처럼 완벽할 수는 없기에 Expresion Blend도 그 개개인에 따라 특징이 있습니다.

지금 공개되어 있는 Expresion Blend는 크게 Expression Blend, Expresion Blend 2, Expresion Blend 2.5 이렇게 3가지가 있는데 우선 그 형제들에 대한 전반적인 내용을 이 글에서 소개하고 각각에 대한 조금 더 자세한 내용은 다음에 다시 준비하겠습니다.

그럼, 제일 맏형 부터 소개해 드리겠습니다.

Expression Blend

Expression Blend는 닷넷 프레임워크 3.0 기반의 작업을 하기 위해 2007년 4월에 처음으로 소개되었으며, Expression Studio의 구성 제품중 하나입니다. 현재 정식버전으로 아래 요약된 모든 기술을 지원합니다.(지금 현재 2007년 5월 3일 버전이 최신이며, SP1이 2008년 3월 6일날 소개되었습니다.)

Expression Blend

Expression Blend 다운 받기

요약
배포상태 정식 버전
지원기술 WPF (3.0)
지원상태 정식 배포


Expression Blend 2 Beta

Expression Blend의 다음 버전으로 WPF만 특화되어 있던 Expression Blend에 실버라이트(1.0, 1.1)를 개발할 수 있게 발전한 제품입니다. 지속적인 버전업에 이어 강력한 새로운 기능들이 추가되어 2008년 2월에 베타 버전(Expression Studio 2)으로 발표되었습니다. 2008년 7월 1일전까지 무제한으로 사용하실 수 있습니다.

Expression Blend 2

Expression Blend 2 다운 받기

요약
배포상태 베타 버전
지원기술 WPF (3.0, 3.5), Silverlight 1.0
지원상태 테스트용


Expression Blend 2.5 March 2008 Preview

MIX08 행사에서 소개된 실버라이트 2 베타 1 기반이나 그 이후의 실버라이트 버전에 대한 작업을 지원하는 제품입니다. Expression Blend 2가 Expression Blend의 미래 버전이라면 Expression Blend 2.5는 Expression Blend 2의 차기 버전으로 생각하시면 더 이해가 빠르실 것 같습니다.

Expression Blend 2.5

Expression Blend 2.5 다운 받기

요약
배포상태 프리뷰 버전
지원기술 Silverlight 2 Beta 1
지원상태 테스트용


뭐 별 내용도 없지만 우선은 한번쯤 블랜드의 가계도를 조사해 볼 필요가 있는듯해서 정리해 보았습니다.
각각에 대한 조금 더 자세한 내용은 빠른 시간안에 정리해서 올리겠습니다.
(댓글은 필수, 짱돌은 사절)


====================================================================================================

※ 엄친아, 엄친딸
 - "엄마 친구 아들, 엄마 친구 딸"이라는 말의 약자로 어머니들이 가끔씩 여러분들과 비교 대상으로 삼는 존재.
ex) "엄마 친구 아들은 맨날 전교 1등인데도 하루 4시간만 자고 공부를 하는데 너는 이게 뭐니"

※ 사족 : Expression Blend가 왜 '그(He)'인가??
  - 우리 죄민수 행님의 대사가 생각납니다.
    "아무 이유없어"
 그냥 제 개인적인 생각으로 Expression Design과 Expression Blend는 둘이 서로 호흡을 같이하며 알콩달콩 사랑을 므흣해야 Xaml이라는 태명의 결과물이 예쁘게 나올것 같은데 Expression Design는 꽃단장이라는 단어가 어울리는 새색시 같은 느낌이고, Expression Blend는 이것저것 닥치는 대로 그것도 성격이 있어서 자기가 할 줄 아는것만 하는 고집불통 머슴아 같은 느낌이라 이렇게 정했습니다.
개인적인 느낌에 태클을 거시는 당신은 박명수~

Posted by UXPRO
Silverlight2008.03.06 07:22
사용자 삽입 이미지

Silverlight2 Beta 1

MIX 08에서 실버라이트 2.0이 그 얼굴을 나타냈습니다.

http://www.microsoft.com/events/executives/webcasts.mspx

새벽 밤을 세우면서 Keynote를 본 뿌듯함이 느껴집니다. ㅎㅎ
Posted by UXPRO