Category Archives: WPF

Settings the DataContext in XAML and the ObjectDataProvider

I was updating a Tips & Tricks post on setting the DataContext via XAML and realised the post was getting way too large for a Tips & Tricks, so here’s the content in its own post.

So to set the DataContext in XAML we can do the following

<Window.DataContext>
   <Thermometer:ConversionViewModel />
</Window.DataContext>

This is simple enough, but there are various other ways to do this in XAML

ObjectDataProvider

The ObjectDataProvider allows us to create an object for use as a binding source within XAML. Unlike the Datacontext shown above, we declare the XAML for the ObjectDataProvider within the Window.Resources section as per

<Window.Resources>
   <ObjectDataProvider ObjectType="{x:Type Thermometer:ConversionViewModel}" x:Key="data">
      <ObjectDataProvider.ConstructorParameters>
         <system:Double>30</system:Double>
      </ObjectDataProvider.ConstructorParameters>
   </ObjectDataProvider>
</Window.Resources>

In the example above you’ll notice we can supply constructor parameters also.

We give the object a key for use in our bindings where we could just do something like

<Grid DataContext="{StaticResource data}">
...
</Grid>

or

<TextBlock Text={Binding Source={StaticResource data}, Path=Name}" />

The ObjectDataProvider also allows us to bind to a Method return value. So for example, what if we have the ObjectDataProvider similar to the one previously declared and we have a method named GetAge which takes a parameter (the name of the person who’s age we want returned). Like the previous example we can declare our ObjectDataProvider in the Resources section and it might look like this

<ObjectDataProvider ObjectInstance="{StaticResource data}" MethodName="GetAge" x:Key="age">
   <ObjectDataProvider.MethodParameters>
      <system:String>Bob</system:String>
   </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

Now we can bind to this data in the following way

<Label Content="{Binding Source={StaticResource age}}" />

Note: Just remember that the binding source is one way. So if you were to assign it to a two way by default control such as a TextBox, you’d get an error requiring you to set the binding to one way (not much use really on a text box).

But it would be much cooler if you could bind to the method and yet interact with the parameters at runtime, i.e. the user enters a person’s name (in our example) and the label updates to show the age of that person.

This can be achieved by creating a binding to the ObjectDataProvider object itself. By default we’ve seen that the interaction with the binding source allows us to pass straight through to the actual data the binding source contains, i.e. we do not appear to be using an ObjectDataProvider to bind to but instead the data source we assigned to it. If we could bind somehow to the ObjectDataProvider itself we could change the arguments passed to the method. This is how we do this…

<TextBox>
   <TextBox.Text>
      <Binding Source="{StaticResource age}" Path="MethodParameters[0]" BindsDirectlyToSource="true" />
   </TextBox.Text>
</TextBox>

As you can see above, we bind to the source as we’ve done previously but we now have a Path that points to the MethodParameters list and we’ve set the BindsDirectlyToSource to true. This tells the binding to evaluate the path on DataSourceProvider object (the ObjectDataProvider) as opposed to our data which is wrapped within the ObjectDataProvider.

Another thing to note about the code above, is that this works fine if the method parameter is a string (as in our example), but if it’s not then you’ll need to convert the type within the TextBox.Text binding source to the type expected by the method or you’ll simply find the method doesn’t get called.

For example

<TextBox.Text>
   <Binding Source="{StaticResource name}" 
                 Path="MethodParameters[0]" BindsDirectlyToSource="true" 
                 Converter="{MyConverters:ConvertTypeConverter To={x:Type system:Int32}}"/>
</TextBox.Text>

And finally…
Just to conclude this tip by also stating that you can also declare your view model in XAML as a resource as in the following

<Window.Resources>
   <Thermometer:ConversionViewModel InitialValue="30" x:Key="data" />
</Window.Resources>

The above shows how we can set properties on the view model as well.

WPF Tips & Tricks

This idea of the tips & tricks is just as a scratch pad for code snippets etc. relating to the subject that don’t warrant a whole post to themselves. Here’s a few WPF tips & tricks.

StringFormat

I seem to always forget this, basically a simple way to apply string formatting to a TextBox (for example) is to use StringFormat

<TextBox Text="{Binding Fahrenheit, StringFormat={}{0:#.##}}" />

The above formats the TextBox string to 2 dp. Fahrenheit in this instance being a float.

Another example with DateTime formatting

<TextBlock Text="{Binding LastUpdateDateTime, StringFormat={}{0:HH:mm:ss dd/MM/yyyy}}" />

Setting the DataContext in XAML

Another one I seem to forget a lot. Admittedly I only tend to use it for simple apps. but still.

<Window.DataContext>
   <Thermometer:ConversionViewModel />
</Window.DataContext>

So we can set the data context on the main window easily enough using this method but there’s also a couple of other ways to create a view model in XAML…

See Settings the DataContext in XAML and the ObjectDataProvider

Order of XAML attributes

A little gotcha to watch out for. Take something like a ComboBox which has the SelectedValue and ItemsSource attributes.

Beware that if SelectedValue appears before ItemsSource you may well find the SelectedValue not set when the binding first takes place. Switch the two around so ItemSource appears first and this should fix the problem.

Detecting whether you’re in design mode

If you need to check whether your control (or general UI) is currently being displayed in design mode, i.e. maybe to not waste time displaying animation or the likes, use

if(!!DesignerProperties.GetIsInDesignMode(this))
{
   // not in design mode
}

Beware d:DesignWidth & d:DesignedHeight as opposed to Height and Width

This is a stupid tip and everyone should know but it’s funny how easy it is to miss this.

I was designing a simple little UI in WPF using both XAML code and the WPF Designer. I made a change to the Width and Height of the control. Unbeknown to me the actual control’s Width and Height were set, not the DesignWidth & DesignHeight. Hence when I placed the control onto another control I couldn’t understand initially why the control was not expanded correctly, when I resized the app.

So beware the WPF designer switching to setting your actual Width and Height as opposed to the d:DesignWidth and d:DesignHeight as it can lead to some head scratching when views are not resizing as expected.

TypeConverters and XAML

When we’re setting margins, backgrounds etc. in XAML we use string representations which get converted to the actual objects. For example

<Button Margin="0,3,0,3" />

in this example the string 0,3,0,3 is converted into a Margin object by the MarginConverter.

Strings are converted to types using TypeConverters. A simple example of one is listed below

public class AbbreviatedNumberConverter : TypeConverter
{
   public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
   {
      return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
   }

   public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
   {
      return destinationType == typeof(InstanceDescriptor) || 
                 base.CanConvertTo(context, destinationType);
   }

   public override object ConvertFrom(ITypeDescriptorContext context, 
                            CultureInfo culture, object value)
   {
      string text = value as string;
      if (text == null)
      {
         return base.ConvertFrom(context, culture, value);
      }

      if (String.IsNullOrWhiteSpace(text))
      {
         return 0.0;
      }

      if (culture == null)
      {
         culture = CultureInfo.CurrentCulture;
      }

      double number;
      if (AbbreviatedNumeric.ValidateDouble(text, out number, culture))
         return number;

      return 0.0;
   }

   public override object ConvertTo(ITypeDescriptorContext context, 
                     CultureInfo culture, object value, Type destinationType)
   {
      if (destinationType != null && value is Double)
      {
         if (destinationType == typeof(string))
         {
            return value.ToString();
 	 }
      }
      return base.ConvertTo(context, culture, value, destinationType);
   }
}

So the above demonstrated a very simple TypeConverter that converts strings like “134m” into 134000000 or the likes of “10k” to 10000. The actual code for the conversion occurs in the AbbreviatedNumeric.ValidateDouble method which I’ll list at the end of this post but will exclude the tests just to save space. This is not an all encompassing converter, it will only convert k for thousands, m for millions and b for billions and also doesn’t handle multiple languages, but it’s here as an example.

Now let’s assume we’ve created some edit control which has an Amount dependency property which we want to allow the user to enter abbreviated numeric strings into. So the dependency property might look like

public Double Amount
{
   get { return (Double)GetValue(AmountProperty); }
   set { SetValue(AmountProperty, value); }
}

public static readonly DependencyProperty AmountProperty =
                    DependencyProperty.Register("Amount", typeof(Double), 
                    typeof(OnlineStatusControl), new PropertyMetadata(0.0));

To apply our type converter we simple add the TypeConverterAttribute to the Amount property as below

[TypeConverter(typeof(AbbreviatedNumberConverter))]
public Double Amount
{
   get { return (Double)GetValue(AmountProperty); }
   set { SetValue(AmountProperty, value); }
}

and finally when using this new control we can do the following

<Controls:AbbreviatedNumericEditor Amount="123m" />

The type converter is called on this and 123m is converted to 123000000 which is now stored as a Double in the dependency property Amount.

For completeness, here’s the simple AbbreviatedNumeric class

public static class AbbreviatedNumeric
{
   public static bool ValidateDouble(string value, out double? numeric, 
              CultureInfo cultureInfo = null)
   {
      double result;
      if(ValidateDouble(value, out result, cultureInfo))
      {
         numeric = result;
         return true;
      }
      numeric = null;
      return false;
   }

   public static bool ValidateDouble(string value, out double numeric, 
              CultureInfo cultureInfo = null)
   {	
      if (String.IsNullOrEmpty(value))
      {
         numeric = 0;
         return false;
      }

      if (Double.TryParse(value, out numeric))
      {
         return true;
      }
      if (value.Length > 0)
      {
         if (cultureInfo == null)
         {
	    cultureInfo = CultureInfo.CurrentCulture;
	 }

	 NumberFormatInfo numberFormat = cultureInfo.NumberFormat;
 	 if (value.Substring(0, 1) == numberFormat.NumberDecimalSeparator)
	 {
	    value = "0" + value;
	 }
	 if (Double.TryParse(value.Substring(0, value.Length - 1), 
                     NumberStyles.AllowLeadingWhite | 
                     NumberStyles.AllowTrailingWhite |                      
                     NumberStyles.AllowLeadingSign |
 		     NumberStyles.AllowDecimalPoint | 
                     NumberStyles.AllowThousands | 
		     NumberStyles.AllowExponent, cultureInfo, out numeric))
	 {
	    switch (Char.ToUpper(value[value.Length - 1]))
	    {
	        case 'B':
		   numeric = numeric * 1000000000;
		   break;
		case 'M':
		   numeric = numeric * 1000000;
		   break;
		case 'K':
		   numeric = numeric * 1000;
		   break;
		default:
		   return false;
	    }
            return true;
	 }
      }
      return false;
   }
}

Quick Start – MahApps Metro

I discovered the excellent MahApps Metro libraries a while back but it wasn’t until I started using github:Windows that I was inspired to really start using this excellent library.

Basically MahApps Metro offers a bunch of styles and controls which duplicate aspects of Windows 8 UI but ofcouse they can be used on non-Windows 8 versions of Windows. For example, I have code on both WinXP and Windows 7 using these libraries and they look great.

This post is just a quick “how to quickly get up and running” with MahApps.

  • Let’s start by creating a WPF Application in Visual Studio.
  • Now using NuGet type MahApps.Metro into the search box of NuGet and install MahApps.Metro
  • In the MainWindow.xaml.cs change the base class from Window to MetroWindow and add using MahApps.Metro.Controls;
  • In the MainWindow.xaml change Window to MetroWindow add the namespace if need be (for example xmlns:Controls=”clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro”)
  • Finally add A Window.Resources section to the MainWindow.xaml file as per the code below to enable the Metro styles
<Window.Resources>
   <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
      </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>
</Window.Resources>

Note: After installing MahApps.Metro using NuGet the page http://mahapps.com/MahApps.Metro/ is displayed, it contains the steps above plus more so obviously read that for a fuller explanation. I’ve written these steps out just to show the bare minimum I need to do to get started.

MarkupExtension

The MarkupExtension is the base class for things like StaticResource, DynamicResource, Binding and so on. It basically allows derived classes to participate in XAML more like a first class citizen.

For example, everyone and their dog has written a BooleanToVisibilityConverter (or those less prone to reinventing the wheel will have used something similar from one of the many WPF/XAML frameworks). But for the sake of this post let’s create one again.

public class BooleanToVisibilityConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter,
                         CultureInfo culture)
   {
      bool result = (value is bool?) ?
                         ((bool?) value).GetValueOrDefault(false) :
                         false;
      if(value is bool)
      {
         result = (bool) value;
      }
      return result ? Visibility.Visible : Visibility.Collapsed;
   }

   public object ConvertBack(object value, Type targetType, object parameter,
                             CultureInfo culture)
   {
      return (value is Visibility) ? (Visibility) value == Visibility.Visible : false;
   }
}

Now to use this in XAML we need to declare it within a ResourceDictionary

<Controls:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />

and to use we do the following

<Button Content="Cancel" Visibility="{Binding IsCancelVisible, 
    Converter={StaticResource BooleanToVisibilityConverter}}" />


There’s absolutely nothing wrong with this approach, but we could alter things slightly by deriving the BooleanToVisibilityConverter from MarkupExtension as per the following

public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter
{
   public override object ProvideValue(IServiceProvider serviceProvider)
   {
      return this;
   }

   // previous code unaltered
}

Now we can remove the entry from the ResourceDictionary and alter the usage in the XAML for the button declaration to

<Button Content="Cancel" Visibility="{Binding IsCancelVisible, 
   Converter={Controls:BooleanToVisibilityConverter}}">


Well you may be thinking that all you gained was the removal of the ResourceDictionary line in the XAML, but actually we’ve now opened up the BooleanToVisibilityConverter to allow it to be more like built in XAML elements.

One thing you might find with alternate BooleanToVisisbilityConverters is that they either use Visibility.Collapsed or Visibility.Hidden for false. Obviously these two Visibility values differ (collapsed allows the parent layout to use the space where a component is collapsed, hidden means the component still takes up space in the layout but is now invisible).

So it’d be nice if out BooleanToVisibilityConverter could have false assigned to either Visibility.Collapsed or Visibility.Hidden depending upon our specific requirement.

So we can change our BooleanToVisibilityConverter source to

public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter
{
   public BooleanToVisibilityConverter()
   {
      WhenFalse = Visibility.Collapsed;
   }

   public BooleanToVisibilityConverter(Visibility whenFalse)
   {
      WhenFalse = whenFalse;
   }

   [ConstructorArgument("WhenFalse")]
   public Visibility WhenFalse { get; set; }

   public override object ProvideValue(IServiceProvider serviceProvider)
   {
      return this;
   }

   public object Convert(object value, Type targetType, object parameter,
                         CultureInfo culture)
   {
      bool result = (value is bool?) ?
                        ((bool?) value).GetValueOrDefault(false) :
                        false;
      if(value is bool)
      {
         result = (bool) value;
      }
      return result ? Visibility.Visible : WhenFalse;
   }

   public object ConvertBack(object value, Type targetType, object parameter,
                             CultureInfo culture)
   {
      return (value is Visibility) ?
                (Visibility) value == Visibility.Visible : false;
   }
}

As you see we’ve now added a new property, WhenFalse, and defaulted this in the constructor and ofcourse altered the return in the Convert method to return WhenFalse when the boolean is false. The ConstructorArgumentAttribute and the non-default constructor are not actually required for this to work, but are here for serialization.

In XAML we now simply declare our button as

<Button Content="Cancel" Visibility="{Binding IsCancelVisible, 
    Converter={FolderViewer:BooleanToVisibilityConverter 
    WhenFalse=Collapsed}}">

Embedding code in your XAML

First off a disclaimer. Just because you can do this doesn’t mean you should :)

<x:Code>
   <![CDATA[
   private void OKButton_Click(object sender, RoutedEventArgs e)
   {
      MessageBox.Show("OK Clicked");
   }
   ]]>            
</x:Code>

<Button Content="OK" Width="80" Margin="3" Click="OKButton_Click" />

There’s not a lot to say about this one except that it’s possible to embed code in XAML. Obviously it’s easier to code it, generally speaking, in the code behind and better still in the view model. But the option is there :)

A simple WPF TriggerAction to turn events into commands

This is nothing new. I know of several MVVM frameworks that do this, but this was my take on a solution for the following:

So you have events on a UIElement, for example a Button has MouseEnter and MouseLeave (amongst others). By default the events require an event handler which would might be placed in the “code behind” in the view itself. But this is no use if, for example a MouseEnter should update some data from the view model unless you want to do more coding in the view to access the view model and makes calls directly on it, which is a somewhat against the spirit of MVVM. So what would be cool is if the MouseEnter could instead be bound to a view model command instead.

Being that part of the mechanism already exists in EventTriggers then we just need to supply a trigger action to bind to the view model.

For example the XAML might look like:

<Button Content="Cancel" Width="80" Margin="3" >
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="MouseEnter">
         <controls:CommandAction Command="{Binding ClearSearch}" />
      </i:EventTrigger>
   </i:Interaction.Triggers>
</Button>

The code for the TriggerAction is simple

public class CommandAction : TriggerAction<DependencyObject>
{
   public static readonly DependencyProperty CommandProperty =
	DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandAction),
	new PropertyMetadata(null, OnCommandChanged));

   public static readonly DependencyProperty CommandParameterProperty =
	DependencyProperty.Register("CommandParameter", typeof(object), typeof(CommandAction),
	new PropertyMetadata(null, OnCommandParameterChanged));

   private IDisposable canExecuteChanged;

   public ICommand Command
   {
      get { return (ICommand)GetValue(CommandProperty); }
      set { SetValue(CommandProperty, value); }
   }

   public object CommandParameter
   {
      get { return GetValue(CommandParameterProperty); }
      set { SetValue(CommandParameterProperty, value); }
   }

   private static void OnCommandChanged(DependencyObject sender, 
                   DependencyPropertyChangedEventArgs e)
   {
      CommandAction ev = sender as CommandAction;
      if(ev != null)
      {
         if (ev.canExecuteChanged != null)
	 {
	    ev.canExecuteChanged.Dispose();
	 }

	 ICommand command = e.NewValue as ICommand;
	 if (command != null)
	 {
	    ev.canExecuteChanged = Observable.FromEventPattern(
			x => command.CanExecuteChanged += x,
			x => command.CanExecuteChanged -= x).Subscribe
			(_ => ev.SynchronizeElementState());
	 }
      }
   }

   private static void OnCommandParameterChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
   {
      CommandAction ev = sender as CommandAction;
      if (ev != null)
      {
         ev.SynchronizeElementState();
      }
   }

   private void SynchronizeElementState()
   {
      ICommand command = Command;
      if (command != null)
      {
         FrameworkElement associatedObject = AssociatedObject as FrameworkElement;
	 if (associatedObject != null)
	 {
	    associatedObject.IsEnabled = command.CanExecute(CommandParameter);
	 }
      }	
   }

   protected override void Invoke(object parameter)
   {
      ICommand command = Command;
      if(command != null)
      {
         command.Execute(CommandParameter);
      }
   }
}

We derive our class from TriggerAction and declare any dependency properties etc. we want on it. So if you ignore all the setting up of Command & CommandParameter code, this really boils down to the override of the Invoke method. This is what’s called when the trigger condition is met.

Blend Behaviors in WPF

A quick post about blend behaviors in WPF. A behavior (from the System.Windows.Interactive assembly) allows us to add functionality to elements within the UI tree. An example might better serve to describe what one is and how to write one.

Let’s make things simple and say we have a UI element which we want to fade into the background when not focus. So we can create a class derived from Behavior<>. Looking at the properties on a UIElement this will suffice for our needs so we’ll derive our FadeOnLostFocusBehavior (bit of a mouthful) from Behavior.

If we jump straight to the code we get something like

public class FadeOnLoseFocusBehavior : Behavior<UIElement>
{
   private const float FADED = 0.2f;

   protected override void OnAttached()
   {
      AssociatedObject.LostFocus += AssociatedObject_LostFocus;
      AssociatedObject.GotFocus += AssociatedObject_GotFocus;

      // this just ensures a default state of faded for the control
      AssociatedObject.Opacity = FADED;

      base.OnAttached();
   }

   protected override void OnDetaching()
   {
      AssociatedObject.LostFocus -= AssociatedObject_LostFocus;
      AssociatedObject.GotFocus -= AssociatedObject_GotFocus;

      base.OnDetaching();
   }

   private void AssociatedObject_LostFocus(object sender, RoutedEventArgs e)
   {
      AssociatedObject.Opacity = FADED;
   }	

   private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e)
   {
      AssociatedObject.Opacity = 1;
   }
}

The above is very simple. When we attach the behavior to the UIElement we connect to the required events on the AssociatedObject. When we detach from the UIElement we detach from the events on the AssociatedObject. The rest is self-explanatory.

The XAML for this example would look like

<Button Content="Cancel" Width="80" Margin="3" >
   <i:Interaction.Behaviors>
      <controls:FadeOnLoseFocusBehavior />
   </i:Interaction.Behaviors>
</Button>

WPF Composite Control

Over the years I’ve implemented this code in Delphi, C++ and C# with WinForms. I finally had reason to implement it again, but now in WPF. There were a few interesting issues to solve, so I’ve listed them below.

1. I wanted a simple EllipseTextBox control. A textbox with associated “…” button. The XAML for this is simple enough (I’ve excluded all the UserControl namespaces etc.).

<Grid>
   <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="Auto" />
   </Grid.ColumnDefinitions>
   <TextBox Grid.Column="0" />
   <Button Grid.Column="1" Content="..." />
</Grid>

Whilst this produces a Button next to a TextBox I obviously needed to add code behind to allow me to bind to the Button Command and TextBox Text properties.

2. So in the code behind I needed to write a few lines of code, but as the TextBox already has a Text property and the Button a Command property, I wanted to set up the relevant DependencyProperty to pass the Text and Command through to the TextBox and Button. To do this I added the following.

public partial class EllipseTextBox : UserControl
{
	public static readonly DependencyProperty TextProperty = TextBox.TextProperty.AddOwner(typeof (EllipseTextBox));
	public static readonly DependencyProperty CommandProperty = ButtonBase.CommandProperty.AddOwner(typeof (EllipseTextBox));

	public EllipseTextBox()
	{
		InitializeComponent();
	}

	public string Text
	{
		get { return (string)GetValue(TextProperty); }
		set { SetValue(TextProperty, value); }
	}

	public ICommand Command
	{
		get { return (ICommand)GetValue(CommandProperty); }
		set { SetValue(CommandProperty, value); }
	}
}

Great so now we can have a TextBox and Button displayed along with the code to pass the Command and Text properties through to the Button and TextBox, but this is of little use of the Command is not hooked up directly to the Button in the UserControl and likewise the Text property on the TextBox. So next step is to wire the XAML to the code behind.

3. Thankfully this isn’t difficult (although it’s rather verbose). So if we update the original XAML replacing the TextBox and Button code with the following

<TextBox Grid.Column="0" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=ControlLibrary:EllipseTextBox, AncestorLevel=1}}" />
<Button Grid.Column="1" Content="..." Width="{Binding ActualHeight, RelativeSource={RelativeSource Self}}" Command="{Binding Command, RelativeSource={RelativeSource FindAncestor, AncestorType=ControlLibrary:EllipseTextBox, AncestorLevel=1}}"/>

Note: Another nice little trick while implementing this was that I wanted the Button to be square – so I’ve got the Button Width binding to the ActualHeight of the Button. Well I thought it was nice :)