Posts
16
Comments
75
Trackbacks
54
giovedì 3 aprile 2008
Find databinding mistakes using PresentationTracesources.TraceLevel in Fx 3.5

Debugging WPF databinding problems can be sometimes a painful experience: consider this simple XAML fragment and its codebehind that doesn’t work due to mistakenly typed CustomerName inside binding expression.

<Window x:Class="WPF_Databind.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml             
    Title="Window1" Height="300" Width="00">
    <Grid>
        <TextBox 
            Text="{Binding Path=CustomerName}"
            Height="23" Margin="87,65,71,0" Name="textBox1" VerticalAlignment="Top" />
    </Grid>
</Window>

 

namespace WPF_Databind { public partial class Window1 : Window { public Window1 () { InitializeComponent(); this.DataContext = new Customer() { Name = "Foo", Id = 42 }; } } public class Customer { public string Name { get; set; } public int Id { get; set; } } }

Running this sample results in an empty Textbox: how do we get hints about what’s wrong with it? , the only place where we can look for a possible reason is Visual Studio output window (see below) and among various output messages search for some useful information like:

System.Windows.Data Error: 35 : BindingExpression path error: 'CustomerName' property not found on 'object' ''Customer' (HashCode=22613453)'. BindingExpression:Path=CustomerName; DataItem='Customer' (HashCode=22613453); target element is 'TextBox' (Name='textBox1'); target property is 'Text' (type 'String')

In some cases this wouldn’t help you much and you’d like to have more details about what’s wrong with your databinding, well starting from .NET Framework 3.5 you can thanks to PresentationTraceSources class.
Let’s modify our previous sample importing System.Diagnostics namespace (that’s where PresentationTraceSources lives even if hosted inside WindowsBase assembly) and applying it to our failing binding.

<Window x:Class="WPF_Databind.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"                
    Title="Window1" Height="300" Width="300">
    <Grid>
        <TextBox 
            Text="{Binding Path=CustomerName,diag:PresentationTraceSources.TraceLevel=High}"
            Height="23" Margin="87,65,71,0" Name="textBox1" VerticalAlignment="Top" />
    </Grid>
</Window>

Running sample again we can see a more verbose description of what really happens behind our binding:

System.Windows.Data Warning: 47 : Created BindingExpression (hash=14421545) for Binding (hash=33163964)
System.Windows.Data Warning: 49 : Path: 'CustomerName'
System.Windows.Data Warning: 51 : BindingExpression (hash=14421545): Default mode resolved to TwoWay
System.Windows.Data Warning: 52 : BindingExpression (hash=14421545): Default update trigger resolved to LostFocus
System.Windows.Data Warning: 53 : BindingExpression (hash=14421545): Attach to System.Windows.Controls.TextBox.Text (hash=35567111)System.Windows.Data Warning: 58 : BindingExpression (hash=14421545): Resolving source
System.Windows.Data Warning: 61 : BindingExpression (hash=14421545): Found data context element: TextBox (hash=35567111) (OK)
System.Windows.Data Warning: 62 : BindingExpression (hash=14421545): DataContext is null
System.Windows.Data Warning: 56 : BindingExpression (hash=14421545): Resolve source deferred
'WPF_Databind.vshost.exe' (Managed): Loaded 'C:\Windows\assembly\GAC_MSIL\PresentationFramework.Aero\3.0.0.0__31bf3856ad364e35\PresentationFramework.Aero.dll'
System.Windows.Data Warning: 58 : BindingExpression (hash=14421545): Resolving source
System.Windows.Data Warning: 61 : BindingExpression (hash=14421545): Found data context element: TextBox (hash=35567111) (OK)
System.Windows.Data Warning: 69 : BindingExpression (hash=14421545): Activate with root item Customer (hash=1669504)
System.Windows.Data Warning: 98 : BindingExpression (hash=14421545): At level 0 - for Customer.CustomerName found accessor <null>
System.Windows.Data Error: 35 : BindingExpression path error: 'CustomerName' property not found on 'object' ''Customer' (HashCode=1669504)'. BindingExpression:Path=CustomerName; DataItem='Customer' (HashCode=1669504); target element is 'TextBox' (Name='textBox1'); target property is 'Text' (type 'String')
System.Windows.Data Warning: 71 : BindingExpression (hash=14421545): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 77 : BindingExpression (hash=14421545): TransferValue - using fallback/default value ''
System.Windows.Data Warning: 78 : BindingExpression (hash=14421545): TransferValue - using final value ''

Available values for TraceLevel property are None,Low, Medium and High which result in different tracing details, and of course, don’t forget to remove it before releasing the application.

Note for Expression Blend users
It looks like that both Expression Blend 2.0 and 2.5 don’t recognize TraceLevel property so you won’t be able to see the artboard in presence of this attibute, but this will certainly be fixed in future releases.

posted @ giovedì 3 aprile 2008 8.58 | Feedback (1)
lunedì 28 agosto 2006
Wanna fix this? :-)

Here I've found an interesting GUI for Sandcastle built by an MVP named Conrad (sounds familiar uh?) did a quick test and looks very promising, unfortunately it has some compiler issues and final chm is not generated.
Author lacks time for investigating problem further so he was kind enough to publish source code (C#)

Is anyone willing to catch the challenge?  

posted @ lunedì 28 agosto 2006 15.15 | Feedback (0)
lunedì 6 marzo 2006
Windows Vista Desktop Window Manager
An interesting post from Greg Schechter about Windows Vista's Desktop Window Manager and how it will change the way application deal with WM_PAINT.
posted @ lunedì 6 marzo 2006 19.15 | Feedback (1)
domenica 26 febbraio 2006
XamlMigrate
Rob Reylea has posted a XamlMigrate tool that helps migration of Xaml files to Feb CTP, really nice job!
posted @ domenica 26 febbraio 2006 17.33 | Feedback (7)
mercoledì 22 febbraio 2006
WinFX Feb CTP Available

WinFX Feb CTP has just been released.
No EID (Sparkle) available yet for this CTP but it will be soon :-)

Karsten has an interesting list of breaking changes.

posted @ mercoledì 22 febbraio 2006 21.07 | Feedback (0)
sabato 18 febbraio 2006
Upcoming XAML changes

Rob Reylea announces some changes that we're gonna find on next WPF CTP.
Apart renaming renaming of xml urins it looks like that we won't need PI instructions anymore for CLR mapping, really hope Cider will handle this better as it does now...
Happy to read that an upgrade tool will be available...

posted @ sabato 18 febbraio 2006 14.02 | Feedback (0)
mercoledì 15 febbraio 2006
EID: Applying style using triggers

“In XAML you can define a style and have it applied based on an Event,Property or DataBinding property change.
To give you an idea, here's a XAML fragment that sets some properties of a button when mouse is over it.

<Style TargetType="{x:Type Button}">
  <Style.Triggers>
    <Trigger Property="IsMouseOver" Value="True">
    <Setter Property="FontSize" Value="20" />
    <Setter Property="Foreground" Value="Red" />
  </Trigger>
 </Style.Triggers>
</Style>

To have the same result using EID (a.k.a “Sparkle”) you have to follow some steps.
Let's try, as demo, to have the background of a button changing when IsMouseOver property is true.

  • Start by drawing a button on scene's document root.
  • Right click and select to Edit a copy of the style (BTW: You can see the structure of original style on EID timeline)
  • Click on Timeline's Create new state button, you should now have a new [No Triggers] tab
  • On Timeline Properties Palette, press Add button and type IsMouseOver on left textbox and true on right one.
  • Now change the backcolor of the button, when finished press Return to scope root button.
  • Test the scene

You'll see backcolor change on MouseOver.
Editing is far than complete, I'm still not able to edit some properties (e.g. Opacity) and looks like that Event/DataBiding triggers are still work in progress, but you should have an idea of how thing should work.”

posted @ mercoledì 15 febbraio 2006 22.50 | Feedback (1)
venerdì 10 febbraio 2006
Using BitmapEffects

“You can easily apply effects like Blur or DropShadows to a UI element using BitmapEffects property.

This xaml sample:

<Image HorizontalAlignment="Left" VerticalAlignment="Top" Source="cor.jpg">
 <Image.BitmapEffect>
  <BitmapEffectGroup>
   <BitmapEffectGroup.Children>
    <BitmapEffectCollection>
      <BlurBitmapEffect Radius="2"/>
      <DropShadowBitmapEffect/>
    </BitmapEffectCollection>
   </BitmapEffectGroup.Children>
  </BitmapEffectGroup>
 </Image.BitmapEffect>
</Image> 
<TextBox Text="Hello WPF">
 <TextBox.BitmapEffect> 
  <BitmapEffectGroup>
    <BitmapEffectGroup.Children>
     <BitmapEffectCollection>
      <OuterGlowBitmapEffect GlowColor="Green" GlowSize="5" Noise="3"  />
      <DropShadowBitmapEffect/>
     </BitmapEffectCollection>
    </BitmapEffectGroup.Children>
  </BitmapEffectGroup> 
 </TextBox.BitmapEffect>
</TextBox>
Produces this effect:

As you can see various effects can be applied to the same element, just keep in mind that effects are processed in sequence so the order of appearance inside counts.”
Unfortunately Sparkle does not support direct editing of this property yet.

posted @ venerdì 10 febbraio 2006 17.52 | Feedback (4)
Databinding using "Sparkle"

How to create a user interface that displays data from an external DataSource using Expression Interactive Designer (“Sparkle“)

  • Create a new Visual C# Library project named PersonsDataSource
  • Remove Class1 and add both Person and Persons class (described in my previous blog)
  • Compile project, you should now have a PersonsDataSource dll.
  • Open Sparkle and create a new Project (File ->New Project) name it as you like.
  • Now let's add a reference to our PersonsDataSource.dll using Project->Add Item to browse to the previously created assembly.
  • You'll now see the dll listed under Project references.
  • Open the Data Palette (View->Data) and select Add new CLR DataSource, browse to PersonsDataSource and select Persons item, you should now see Persons listed inside Data palette.
  • Select Persons item from Data palette and drag it to Document root surface
  • You'll be asked to select how the Persons datasource will be displayed, select ListBox and click Ok.
  • The Create Data Template appears: This dialog allows you to 'shape' the DataTemplate associated to Person object, you can select what items and what controls to map to various Person fields (in this case dialog defaults to TextBlocks) leave defaults and click Ok.
  • You'll should see the listbox filled with Persons items.
  • We now want to add 2 texboxes that will be populated with Listbox selected item.
  • Select Library palette and drag two textboxes on DocumentRoot surface.
  • Select first texbox and, on Properties palette, click on Text field and select DataBind...
  • You'll now see the Create Data Binding dialog, we need to bind to Listbox selected item so click on Element Property and select ListBox.
  • Select SelectedItem among ListBox properties.
  • Listbox contains instances of Person classes so, select Use custom path expression and type “SelectedItem.Name” (without quotes) on related textbox, then click Ok.
  • Do the same with other textbox using “SelectedItem.Age” as custom path expression.
  • Press F5 and you'll see that selecting a listbox item selection will be reflected on both textboxes and that changes on textbox contents will be moved to underlying DataSource.
posted @ venerdì 10 febbraio 2006 13.59 | Feedback (0)
giovedì 9 febbraio 2006
A little bit of WPF DataBinding...

Let's assume you wish to use DataBinding to manage a set of Person class instances.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

 public class Person
 {
  public Person (string name, int age)
  {
   this.Name = name;
   this.Age = age;
  }

  private int mAge;
  public int Age
  {
   get { return mAge; }
   set { mAge = value; }
  }

  private string mName;
  public string Name
  {
   get { return mName; }
   set { mName = value; }
  }

  public override string ToString ()
  {
   return this.Name + " : " + this.Age.ToString();
  }

Now we create a Persons class inheriting from generic ObservableCollection

public class Persons:ObservableCollection<Person>
 {
  public Persons ()
  {
   base.Add(new Person("Corrado",22));
   base.Add(new Person("Giulia",1));
   base.Add(new Person("Stefania",10));
  }
 }


We now use ObjectDataSource to create Persons instance and have it available as DataContext inside xaml.

<?Mapping XmlNamespace="tds" ClrNamespace="Demo" ?>
<Window x:Class="Demo.Window1"
    xmlns="
http://schemas.microsoft.com/winfx/avalon/2005"
    xmlns:x="
http://schemas.microsoft.com/winfx/xaml/2005"
    xmlns:tds="tds"
    Title="Demo"
 >
 <Window.Resources>
  <ObjectDataProvider x:Key="Persons" ObjectType="{x:Type tds:Persons}"  />
  
  <DataTemplate DataType="{x:Type tds:Person}">
   <StackPanel Orientation="Horizontal">
    <TextBlock Foreground="Red" Text="{Binding Name}" FontSize="14" />
    <TextBlock Foreground="Blue" Text="{Binding Age}" FontSize="14"/>
   </StackPanel>
  </DataTemplate>  

 </Window.Resources>

<Grid>
   <ListBox ItemsSource="{Binding Source={StaticResource Persons}}" />    
</Grid>
</Window>
    
       
   
Red lines are namespace to Xml mapping instructions (syntax is probably going to be modified on next CTP)
Magenta line is the ObjectDataProvider definition that allows us to use Person list as datasource on the listbox.
Green lines indicates that both ObjectDataProvider and DataTemplate objects are part of Windows Resources.
DataTemplate (in blue) describes how the UI should display the Person instance (otherwise the ToString() method it will be invoked) in this case I decided to use a StackPanel containing two textblocks both binding to Person properties.
Data are databound to listbox by ItemSource attribute (in orange)
Datatemplates are required because on WPF ItemsControls (like ListBox) are not limited to strings but can contain virtually everything.

Just a simpe demo, but as you know, we all need a starting point... :-)

posted @ giovedì 9 febbraio 2006 23.34 | Feedback (117)
News

This is my personal blog.
These postings are provided "AS IS" with no warranties, and confer no rights.

Disciple