Friday, July 28, 2006

Just a little tip, showcasing the power of Xaml and the efficiency of good code/design separation.

When you are fetching data from a server, you could (and actually should) use the DataModel-View-ViewModel pattern, as described by Dan Crevier from the Microsoft Max team. It uses a viewmodel-class to bind your Xaml against. Dan then implements a 'state' property to indicate whether the model is finished fetching and is in a 'bindable' state.

If you are short on time, or have other reasons not to implement such a strategy, you are probably binding straight to objects that are still Null during the fetch-action.
In either case, it would be nice to let the user know that data is being fetched.

In my case, I had a lot of <TabItem>'s that are being filled with data, one-by-one, by setting the datacontext directly. While designing the user interface, I do not want to have to think about the possibility of binding against an invalid object (it being null). So I created a style, that I put in the application resources. The style replaces my content-template with a temporary template, whilst in invalid state. I was extremely satisfied with the solution, because it was so dead-easy, and it works like a charm.

Here is the code (don't mock my visually stunning border please ;-) ):

    <Style BasedOn="{StaticResource {x:Type TabItem}}" TargetType="{x:Type TabItem}">

      <Style.Triggers>

        <Trigger Property="DataContext" Value="{x:Null}">

          <Setter Property="ContentTemplate">

            <Setter.Value>

              <DataTemplate>

                <Border CornerRadius="5" BorderThickness="2" BorderBrush="Black" Background="Yellow" Height="60" Width="280"

                        HorizontalAlignment="Center" VerticalAlignment="Center">

                  <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Data is being fetched</TextBlock>

                </Border>

              </DataTemplate>

            </Setter.Value>

          </Setter>

        </Trigger>

      </Style.Triggers>

    </Style>

I was pleasantly surprised by the simplicity of the code. The DataContext is used in a trigger to set the content-template.

Friday, July 28, 2006 2:48:29 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback
 Wednesday, July 26, 2006

Microsoft apparently had reasons not shipping WPF with a datepicker control. In my opinion such a control is of great importance when you are building applications. How can I sell a platform to a client when I have to explain that they won't be able to visually enter a date? (Or have to hire me to build such a control for them ;-) )
Some time ago I started a forum thread about this issue and the ATC Avalon responded by taking up the challenge and started working on a control. Why that team was dismissed is beyond me, but Kevin Moore finished where they left off. He has posted an update to his bag-of-tricks for the July CTP (they also work on the June CTP), and has included the datepicker sample!

I've quickly checked it out and it's looking great! I wish I could use empty dates though, but that should be easy to hack in.
Thanks Kevin!

Wednesday, July 26, 2006 9:42:24 AM (Romance Standard Time, UTC+01:00)  #    Comments [2]  |  Trackback
 Wednesday, July 12, 2006

I love Dependency Properties. Especially attached properties. There is just something extremely cool about being able to think up some property and then setting that in a datatemplate. For instance, creating a custom panel with your own attached properties, and reading these properties during the measure and arrange bits of the layout.
But when you do a get on the property, you will find your left with an unset value!

The backing mechanism for such properties use the object you set them on as a key. When you only have a UIElement, you can not read the value using the UIElement, because you never bound the property to a UIElement, but to your own visual in the datatemplate.
So always remember to use the original object when you are getting your value.

In the case of the UIElement in an itemscontrol, you will find that it is actually a wrapper around your original visual. Get to it by using the infamous visual tree helper:

DependencyObject o = VisualTreeHelper.GetChild(uie, 0);

Then use 'o' in your getvalue!

Wednesday, July 12, 2006 9:39:06 AM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback
 Tuesday, June 20, 2006

The sdk team has published all the WPF beta 2 samples as a zip. They are right here, http://www.wcsdkteam.members.winisp.net/wpfsamples.zip. Leave comments about problematic downloads at the sdk blog.

Tuesday, June 20, 2006 1:35:01 PM (Romance Standard Time, UTC+01:00)  #    Comments [1]  |  Trackback
 Tuesday, June 13, 2006

POCO power is announced by Roger Johansson, a lead developer of the NPersist OR-Mapper.
He writes: 'NPersist entities now supports 2 way databinding and edit cancels straight out of the box while still being fully POCO.
So as far as I know,
NPersist is the only .NET mapper capable of this while being POCO (at design time that is)'

The question I ask myself is, do you really want this? I admit I haven't used npersist for long, because I switched to nHibernate. But, having read Roger's blog for some time, I believe they are quite advanced in the proxy area, using IL.Emits all over the place for incredible speed (the only way to do it!). They certainly seem to have taken this path, giving as much luxury to the developer by doing all kinds of stuff dynamically. And yes, edit cancellation certainly seem like a nice feature to have out of the box. 2 way binding as well.

But then again, what if I want to switch to WPF? It supports the old way of propertynameChanged events, but I'd rather use the new Avalon flavor.
And I have built my own canceling, by using structs as the backing store of my properties. What if I want the 'loaded' state of my objects to also serialize, then I want my own solution where I can easily do that.

By doing too many things that are hard to follow for a developer, you will confuse them.
Most importantly, by doing too many things, you are locking developers into your technology.

I'm against that.

Then again, I'm also a bit jealous. I had to do all of that myself! I hope that their puzzle-framework uses a pluggable architecture, where you use a configuration file to 'plug in' capabilities to the proxy system, even allowing custom capabilities to be created. That would be awesome.

 

(If your into that kind of stuff, your best bet is the Castle framework. Check it out.)

Tuesday, June 13, 2006 12:19:48 PM (Romance Standard Time, UTC+01:00)  #    Comments [2]  |  Trackback
 Monday, June 12, 2006

When you are creating a layout in Xaml, you should be careful to take into account the width you have left. Yes, WPF will try to be smart and scale your controls, but what if the content of your control does not want to be scaled?

Paste this into Xaml-Pad and resize your Window:

<Grid Width="Auto" Height="40" xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
            xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
            xmlns:d='clr-namespace:System.Windows.Data;assembly=PresentationFramework' >
<Button HorizontalAlignment="Left">A lengthy button</Button>
<TextBlock HorizontalAlignment="Center">An longer TextBlock</TextBlock>
</Grid>

Nick Thuesen has a solution for this. He has created 3 rangeConverters that allow you to plug in a width and set a range where you would like your control to be visible. That is cool, I like it, I will use it.
In my specific case though, I wanted to collapse the content of a control based on the width of it's container. Basically, the container is a border, and it's content is a stack panel with some text boxes. The container is sized by an algorithm, so the container is more important then the content. The panel that does this scaling is surrounded by a slider, which zooms the controls accordingly. When enough space is available, the content should become visible.
Since I do not know the range in which the content should be shown, I can't use his controls.

It was dead simple to create my own though. Instead of using a single binding converter, I've used the MultiValueConverter to be able to bind to multiple properties.

public class ClippingToVisibilityHiddenConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
Debug.Assert(values.Length == 2);

double availableWidth = Double.PositiveInfinity;
Double.TryParse(values[0].ToString(), out availableWidth);

double desiredWidth = 0d;
Double.TryParse(values[1].ToString(), out desiredWidth); // possibly unset

double margin = 0d;
if (parameter != null)
Double.TryParse(parameter.ToString(), out margin);

Console.WriteLine("Desired: {0}, avail: {1}", values[1].ToString(), availableWidth.ToString());
return desiredWidth > (availableWidth-margin) ? Visibility.Collapsed : Visibility.Visible;
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new Exception("not implemented");
}
}

Usage is equally simple:

<StackPanel.Visibility>
<
MultiBinding Converter="{StaticResource ClippingConverter}" ConverterParameter="15" >
<
Binding Path="ActualWidth" RelativeSource="{RelativeSource AncestorType={x:Type ContentPresenter}, AncestorLevel=1}" />
<
Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}" />
</
MultiBinding>
</
StackPanel.Visibility>

There you go, I hope you're happy with it! Confusion though about the ActualWidth property of elements....

My custom panel that does the layout, determines the desired size of the elements by doing a measurement of the element. Then at the arrange-pass, it calls an arrange on the element with a size possibly smaller then it desires. Somehow, when you read back the ActualWidth, DesiredSize, RenderSize or what else you can think of, you will never find that passed-in size.

Well, call me st00pid, but I would have expected the RenderSize to let me get to the .... rendered size..  ;-)
It does not.

Since I so desperately do want to find that 'clipped' size, I set the render size myself, after the arrange:

Size s = new Size(days * pixelsPerDay, uie.DesiredSize.Height);
uie.Arrange(new Rect(new Point(tsLinks.Days * pixelsPerDay, 0), s));
uie.RenderSize = s; // oh dear

It's definition in the SDK: Gets (or sets, but see Remarks) the final render size of this element.
So, the remarks then: Do not attempt to set this property, either in XAML or in code, if using the Windows Presentation Foundation (formerly code-named "Avalon") framework-implemented layout manager (nearly all common application scenarios will be using this framework layout manager). The layout manager will not respect sizes set via this property directly...

Yikes.

I like feeling naughty, but feeling this naughty can't be good.
I'll keep it in though, until I find a way to bind to the actual ActualWidth.

Monday, June 12, 2006 2:38:30 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback

Everybody (and their grandmother) has blogged about the name change of winfx to .Net Framework 3.0. Their grievances are mostly focused on the weird dependencies that are created: framework 3.0 relies on framework 2.0 to be installed?! Also, winfx is perceived as a very cool name by the masses (me included!).

But when you think about it, this also allow you to tell your clients: 'you need the .Net Framework 3.0 installed to run this incredible piece of software'. They will also be much more inclined to install an update, versus an add-on.
So, it is very confusing, but in the end maybe for the best.

Brad Adams is answering questions.

Monday, June 12, 2006 1:41:14 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback
 Thursday, June 08, 2006

I always use Expression Interactive Designer when I want to see the full default style of a control, but here I have found a equally easy way: just dump it into XML.

Style style = FindResources(typeof(Button)) as Style; //Get button's default Style
if (style != null)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = new string(' ', 4);
StringBuilder strbuild = new StringBuilder();
XmlWriter xmlwrite = XmlWriter.Create(strbuild, settings);
XamlWriter.Save(style, xmlwrite);//Use XamlWriter to dump the style
return strbuild.ToString();
}

It uses the findresources method to find a style and then just writes it out. Might come in handy!

Thursday, June 08, 2006 7:43:13 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]  |  Trackback
 Wednesday, June 07, 2006

My previous post was about not being able to bind to a named element outside of your scope. With the help of some great people, we figured out a workaround: you can bind to an ancestor. So, this does work:

<StackPanel DataContext="{Binding ElementName=lb, Path=SelectedItem}">
<
ListBox Name="lb" ItemsSource="{Binding Source={StaticResource InventoryData}, XPath='Book'}" IsSynchronizedWithCurrentItem="True" />
<
local:CustomItemsControl ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}, Path=DataContext}" />
</StackPanel>

This has a listbox that binds to a datasource (xml this time) and a stackpanel above it binds it's datacontext to the selecteditem of the listbox.
Obviously this has all kinds of nasty smells surrounding it.... Next please!

We might not be able to bind to a named element outside of scope, but if we can bind to an ancestor, chances are good that we can bind to a staticResource as well. So let's introduce a CollectionView around our XML datasource. In the Window.Resources:
<CollectionViewSource x:Key="InventoryView" Source="{Binding Source={StaticResource InventoryData}, XPath='Book'}" />

And then we can bind to the currentitem of this view, instead of the ugly datacontext of the parent stackpanel:

<StackPanel >
<
ListBox Name="lb" ItemsSource="{Binding Source={StaticResource InventoryView}}" IsSynchronizedWithCurrentItem="True" />
<
local:CustomItemsControl ItemsSource="{Binding Source={StaticResource InventoryView}, Path=CurrentItem}" />
</
StackPanel>

This is a good enough workaround for now. ;-)

Wednesday, June 07, 2006 7:40:44 PM (Romance Standard Time, UTC+01:00)  #    Comments [2]  |  Trackback