Archive for the ‘WPF’ Category

ElementName Binding In ToolTips (Borrowing a NameScope)

July 17, 2008

I had previously seen mention of the limitation that you cannot use ElementName binding within a ToolTip but I never bothered to investigate it since I didn’t have need to use it. Yesterday Josh asked me about it so I decided to look into it further. I’m going to deal with ToolTip here since that was the one he asked me about but I believe the same technique could apply to ContextMenu.

First let’s take a look at the various ways you can define a tooltip that uses ElementName in a binding and see which work.

<Window.Resources>
    <!– Shared tooltip –>
    <ToolTip x:Key=”sharedTT”>
        <TextBlock Text=”{Binding ElementName=txt, 
           Path=Text}” />
    </ToolTip>
</Window.Resources>
<DockPanel>
    <TextBox Text=”This is the tooltip text” 
            x:Name=”txt” DockPanel.Dock=”Top” />
   
    <!– 1 – explicitly provide a tooltip instance where
        the content is bound –>
    <Button Content=”Explicit ToolTip” DockPanel.Dock=”Top” >
        <ToolTipService.ToolTip>
            <ToolTip Content=”{Binding ElementName=txt, 
               Path=Text}” />
        </ToolTipService.ToolTip>
    </Button>
   
    <!– 2 – Set the tooltip to a binding –>
    <Button DockPanel.Dock=”Top” Content=”Binding”
           ToolTipService.ToolTip=”{Binding ElementName=txt, 
           Path=Text}”/>

 

    <!– 3- Set the tooltip to an object that tries to
        bind to an element outside the tooltip –>
    <Button DockPanel.Dock=”Top” Content=”Element ToolTip”>
        <ToolTipService.ToolTip>
            <TextBlock Text=”{Binding ElementName=txt, 
               Path=Text}” />
        </ToolTipService.ToolTip>
    </Button>

 

    <!– 4- Set the tooltip to an element that tries to bind
        to the value of another element within the tooltip –>
    <Button DockPanel.Dock=”Top” >
        <ToolTipService.ToolTip>
            <StackPanel>
                <TextBlock x:Name=”ttText” Text=”Foo” />
                <TextBlock Text=”{Binding ElementName=ttText, 
                   Path=Text}” />
            </StackPanel>
        </ToolTipService.ToolTip>
        Normal ToolTip
    </Button>

 

    <!– 5 – Bind to a ToolTip in Resources –>
    <Button DockPanel.Dock=”Top” 
           Content=”SharedResource ToolTip”
           ToolTipService.ToolTip=”{StaticResource sharedTT}”/>
</DockPanel>

Of all of these the only one that actually works is #2 where the ToolTip property is set to a Binding instance. Suprisingly, at least to me, is that even #4 where we are trying to bind to another element within the tooltip itself does not work.

In order to understand why these aren’t working, we need to understand how ElementName binding works. Basically, when an ElementName is used in a binding, the NameScope of the target object is used to locate the element with the specified name. If that element doesn’t have a NameScope specifically on it, the FrameworkElement.FindScope method continues up the logical tree and falls back to the inheritance context if there is no logical parent. The name scope is the object in which all named objects have been registered. So in this example, there is a NameScope created for the Window itself implicitly. Other objects also provide a namescope to prevent conflicts between names – e.g. ControlTemplate and Style. Actually in those cases, the objects themselves implement INameScope.

The ToolTip however is not part of the logical nor visual tree of the element on which it is being set. Instead, it is just the value of a property and as such it doesn’t have a way to reach the NameScope of the Window in which it was created. The reason that #2 worked is because we just set the value of the ToolTip property to a binding. Since that is a property set directly on the element, that binding has access to the namescope just as you can use in a binding for any other dependency property on the element.

So the issue we have to overcome is how to provide a way for the ToolTip to get to the NameScope of the Window. My solution was to set the NameScope of the ToolTip to a custom INameScope implementation that would get to the NameScope of the element for which the ToolTip was being used. To accomplish this, I defined a new attached property named BindableToolTip. When set, it would set the NameScope property of the tooltip (and create a tooltip if the value wasn’t a tooltip instance such as the case where you are just providing the elements that make up the content of the tooltip) to my custom INameScope implementation that would “borrow” the namescope of the element on which the tooltip was being set. I then set the real ToolTipService.ToolTip property to that tooltip instance.

I did hit one glitch along the way. The BamlRecordReader class which is used to process the compiled baml uses a stack to manage the namescopes it encounters. By the time that the BindableToolTip property change is invoked, the BamlRecordReader has already processed the ToolTip instance (through its PushContext method). So when it gets to the point where it wants to clean up its namescope stack (in its PopContext method), it finds that the tooltip now has a namescope and tries to pop an item off its stack which results in an exception because it tries to pop off more items then it pushed. To get around this, I remove the namescope from the tooltip in the Initialized event of the tooltip.

To use the new functionality, you would just replace any place you are setting the ToolTip property with the BindableToolTip property. After doing so with the sample above, every case now works. I’ve attached the sample project that defines and uses this new attached property.

Who set the DataContext?

July 14, 2008

In the course of the last month or so, several people have asked why the DataContext that they set on the form level wasn’t carried down deeper into their element tree. Since I haven’t seen any documentation going into this I’d like to go over when/why the DataContext may be explicitly set in the WPF framework.

The DataContext is an inherited property defined on FrameworkElement and on FrameworkContextElement (the latter is actually an AddOwner of the former but I’ll discuss AddOwner another day). Suffice it to say that if you set the DataContext on an element, it should/will get inherited by its descendant elements. So naturally some people will assume that if they set it on their Window/Page, that all elements within that Window/Page will get that DataContext value. Afterall they are not setting it anywhere else. Well, that is the problem. While they may not be setting it, the WPF framework does in certain situations and if you look at it you can understand why. So if anything, including within the WPF framework itself, sets the DataContext on one of the descandants of that Window/Page, then all its descandants will get its locally set DataContext instead of the one set on one of its ancestors.

Ok so when will the WPF framework actually set the DataContext? There are actually two situations that I know of in which a class in the WPF framework will set the DataContext and both relate to when it automatically generates an element for you. One is in the ItemsControl – or more accurately by the ItemContainerGenerator of an ItemsControl when a container element is generated for an element in the list. The other is in the ContentPresenter when an element is generated for its Content (e.g. based on a DataTemplate). This makes perfect sense since after all the element generated for the ItemsControl and the elements within the DataTemplate need to get access to the thing that that element is supposed to represent.

The reason this may not be noticed in normal usage is because inherited properties prefer the logical tree and therefore can “skip” over the elements that have had their DataContext set further up the visual tree between it and its logical parent. So for example, if you were to put a TextBlock into a ListBox:

    <Grid DataContext=”Foo”>
        <ListBox>
            <TextBlock Text=”{Binding}” />
        </ListBox>
    </Grid> 

At runtime, a ListBoxItem would be created to contain the TextBlock within the ListBox. The DataContext of that ListBoxItem is the TextBlock (i.e. the object it represents within the listbox). However, the DataContext of the TextBlock ends up being Foo since that is the DataContext of its logical parent (i.e. the ListBox) and would show “Foo” as its Text.

If the TextBlock were not a logical child of the listbox (e.g. if it were added to the listbox via its ItemsSource) then it would inherit the DataContext of its visual parent – which ultimately would come from the ListBoxItem.

    <Grid DataContext=”Foo”>
        <Grid.Resources>
            <x:Array x:Key=”arr” Type=”sys:Object”>
                <TextBlock Text=”{Binding}” />
            </x:Array>
        </Grid.Resources>
        <ListBox ItemsSource=”{StaticResource arr}” />
    </Grid> 

In this case, the TextBlock would have a Text value of “System.Windows.Control.TextBlock” – the ToString of the TextBlock itself since it is the DataContext of the ListBoxItem and therefore that is its DataContext.

PropertyDescriptor AddValueChanged Alternative

April 7, 2008

I’ve been meaning to write about this for a while since I’ve seen this approach mentioned lots of times on the newsgroups but have seen no mentions about the caveats. Just today I saw the same problem in some code from one of the disciples. The scenario is that you want to know when the value of a dependency property changes but you don’t have a one to one relationship with the object. For example, you have a list of items and you want to know when the IsSelected property of an item has changed.

The solution that I have seen given for this is to get to the PropertyDescriptor and use its AddValueChanged method to provide an EventHandler to receive a notification when the property has changed. Sometimes, the reply will mention/use DependencyPropertyDescriptor directly but its the same thing since that is just a derived PropertyDescriptor that provides additional information about the underlying DependencyProperty it represents. You  can get to this property descriptor in a few ways but the most common are to get it from the TypeDescriptor.GetProperties method or using the DependencyPropertyDescriptor.FromProperty.

The issue with this approach is that it will root your object so it will never get collected by the GC. There have been plenty of discussions about how hooking events (particularly static events) can root your object so I won’t go into great detail there. While it does not seem that you are hooking a static event in this case, in essence you are. When you add a handler to a property descriptor, that property descriptor stores the delegate in a hashtable keyed by the object whose property you are hooking. A delegate/handler is basically a pointer to a method on an object (or no object if its for a static method) so that means the property descriptor has a reference to your object as well as the object whose value you are watching (since that is the key into the hashtable). The property descriptors themselves are cached statically so the hashtable is kept around and therefore your object and the one you are watching are as well.

I personally like to use the Scitech memory profiler (or you can use the Microsoft CLR Profiler) when debugging memory leak issues but you can see the issue manifest itself pretty easily in this case. First we’ll do a benchmark to make sure that we can check whether the object was collected.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

If you run this code and check isAlive, you will see that it returns false indicating that the ListBoxItem was not referenced and was able to be collected. Now let’s try using the AddValueChanged method.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(ListBoxItem))[“IsSelected”];
// the following yields the same pd
//PropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ListBoxItem.IsSelectedProperty, typeof(ListBoxItem));
prop.AddValueChanged(i, new EventHandler(this.OnValueChanged));
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

This time isAlive returns true because the property descriptor is maintaining a reference to the ListBoxItem. Now, let’s try an alternative approach that involves creating a helper class to listen for the property change.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
PropertyChangeNotifier notifier = new PropertyChangeNotifier(i, “IsSelected”);
notifier.ValueChanged += new EventHandler(OnValueChanged);
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

In this case isAlive is false indicating that the object can be collected even though we’re still maintaining an explicit reference to the notifier. The implementation for the class – PropertyChangeNotifier – is listed below. The class is basically a simple DependencyObject that exposes 2 properties – Value returns the value of the property of the object that it is watching and PropertySource returns the object whose property it is watching. The constructor for the object takes the object whose property is to be watched for changes and the property that should be watched. This class takes advantage of the fact that bindings use weak references to manage associations so the class will not root the object who property changes it is watching. It also uses a WeakReference to maintain a reference to the object whose property it is watching without rooting that object. In this way, you can maintain a collection of these objects so that you can unhook the property change later without worrying about that collection rooting the object whose values you are watching.

public sealed class PropertyChangeNotifier :
DependencyObject,
IDisposable
{
#region Member Variables
private WeakReference _propertySource;
#endregion // Member Variables
 
#region Constructor
public PropertyChangeNotifier(DependencyObject propertySource, string path)
: this(propertySource, new PropertyPath(path))
{
}
public PropertyChangeNotifier(DependencyObject propertySource, DependencyProperty property)
: this(propertySource, new PropertyPath(property))
{
}
public PropertyChangeNotifier(DependencyObject propertySource, PropertyPath property)
{
if (null == propertySource)
throw new ArgumentNullException(“propertySource”);
if (null == property)
throw new ArgumentNullException(“property”);
this._propertySource = new WeakReference(propertySource);
Binding binding = new Binding();
binding.Path = property;
binding.Mode = BindingMode.OneWay;
binding.Source = propertySource;
BindingOperations.SetBinding(this, ValueProperty, binding);
}
#endregion // Constructor
 
#region PropertySource
public DependencyObject PropertySource
{
get 
{
try
{
// note, it is possible that accessing the target property
// will result in an exception so i’ve wrapped this check
// in a try catch
return this._propertySource.IsAlive
? this._propertySource.Target as DependencyObject
: null;
}
catch
{
return null;
}
}
}
#endregion // PropertySource
 
#region Value
/// <summary>
/// Identifies the <see cref=”Value”/> dependency property
/// </summary>
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(“Value”,
typeof(object), typeof(PropertyChangeNotifier), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnPropertyChanged)));
 
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PropertyChangeNotifier notifier = (PropertyChangeNotifier)d;
if (null != notifier.ValueChanged)
notifier.ValueChanged(notifier, EventArgs.Empty);
}
 
/// <summary>
/// Returns/sets the value of the property
/// </summary>
/// <seealso cref=”ValueProperty”/>
[Description(“Returns/sets the value of the property”)]
[Category(“Behavior”)]
[Bindable(true)]
public object Value
{
get
{
return (object)this.GetValue(PropertyChangeNotifier.ValueProperty);
}
set
{
this.SetValue(PropertyChangeNotifier.ValueProperty, value);
}
}
#endregion //Value
 
#region Events
public event EventHandler ValueChanged;
#endregion // Events
 
#region IDisposable Members
public void Dispose()
{
BindingOperations.ClearBinding(this, ValueProperty);
}
#endregion
}

Another possible approach would be to implement your own derived WeakEventManager but I’ll leave that as an exercise for the reader. For those that choose to go this route, there is such a class – except its internal – in the PresentationFramework assembly.

Compare Property & Field Values with Mole

January 15, 2008

As seems to happen with Mole, a suggestion quickly snowballed into a feature implementation. Mole now has the ability to save the members (properties/fields) of the selected element to an xml file and allow you to load that xml file back in to allow property comparison. This will be extremely helpful when you’re trying to debug a problem where something works for one element but doesn’t for another instance. There’s even an option to filter out members with the same value so you can see just the properties that differ.

 You can download the latest version here.

In addition, Karl has been posting some videos on YouTube that show how to use Mole. You can view those videos here.

Editing Properties and Fields with Mole

January 1, 2008

When debugging there are often times when you need to manipulate the value of a property or field within the watch window. Mole is a great visualizer that lets inspect the properties/fields of other objects in the visual/logical tree but if you saw something that needed to be changed, you would have to come out of the visualizer, change the value (assuming you could easily write the code necessary in the watch window Name column to locate the appropriate object) and then continue debugging.

Well, one of the things that I really wanted to see in Mole was editing capability similar to that of Snoop so we took the time and added it in. I wrote the editing infrastructure making use of .NET’s TypeConverters and Karl wrote the editors making it easy to edit common data types like fonts, colors, enums, etc. You can check it out here.

Note, there are some limitations to what can be done. For example, you can’t create new instances of classes as you might be able to do with the watch window. Since we’re using typeconverters, the editing is limited to the typeconverter associated with the property/field type. Maybe this is something we can look to add in a future version.

Mole for Visual Studio

December 15, 2007

Karl is at it again. He extended Mole to allow it to be used for other types of objects including WinForms Controls, ASP.Net controls, etc. You can read about it on Mole’s home page or on codeproject.

Karl is very kind in his mentions of my involvement. I did help more with this version but Karl is the main one to thank for this round of enhancements. In any case, I highly advise you to try it out. If you have any comments or suggestions, be sure to send them to molefeedback@yahoo.com.

Mole II

December 13, 2007

Josh Smith and I worked together at the Infragistics WinForms development lab and since I’m now working on WPF, I keep an eye on his blog. I also tend to read through the articles on codeproject. So when I saw that he posted a visualizer for wpf, I was naturally curious. I sent him a couple of thoughts about how he might want to change the visualizer.

If you’re not familiar with visualizers, you can check out this page on Microsoft’s site. Basically a visualizer is a tool used for debugging in Visual Studio. It allows you to provide a “visualization” or representation – hence the name – of an object in the program being debugged. They’re actually very powerful because they allow you to send information back and forth between the debugger and debuggee side.

Anyway, Josh then moved on to work on Mole with Karl Shifflett. I posted a bunch of performance related improvements as well as a number of suggestions (delving/drilling into the properties of objects, viewing the logical tree, etc). In the communications with Josh and Karl that followed, I was asked if I wanted to participate in the development with them.

Karl and Josh worked long hours in developing Mole II. I tried to help out where I could but given my schedule (work and personal) I couldn’t help as much as I would have liked. That aside, Josh and Karl were kind enough to include me as an author on the article. I have to say that both Josh and Karl are talented developers. Since I had worked with Josh before I knew he was intelligent and motivated. I hadn’t had the opportunity to work with Karl before but I must say that he is one of the most enthusiastic and driven developers that I have come across. I think the outcome is a great visualizer for inspecting WPF objects.