tags:

views:

98

answers:

3

I have a lot of XAML code and would like to stay compatible with WPF 3.0 while taking advantage of the WPF 4.0 features. For example, I'd like to use UseLayoutRounding if it's available. Of course, I could do this in C#: void SetProperty(..)

{
#if WPF4
 set property
#endif
}

Is there an elegant way to accomplish the same thing in XAML?

+3  A: 

i think you can solve your problem with a class extending MarkupExtension:

[MarkupExtensionReturnType(typeof(bool))]
public class IsWPF4Extension : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
      #if WPF4
      return true;
      #endif
      return false;
}
}

than in xaml you can use it like that:

<MyControl UseLayoutRounding="{IsWPF4}"/>
Marcel
Great solution, I like that syntax
Paul Betts
This does not solve my problem because UseLayoutRounding is not defined in WPF 3.0
tom greene
sorry tom, i forgot that...
Marcel
A: 

If you just want to use "UseLayoutRounding" property, you don't need to.

Because this value is true by default and Microsoft doesn't suggest you to turn it off, and also doesn't suggest you to explicitly set it to true.

redjackwong
Not true: UseLayoutRounding is set to false by default.
tom greene
A: 

I would do it programmatically like, because this way you dont have to touch your xaml code.

Call this method after you initialized your layout root and set all the things you need in wpf 4.

public static void SetLayoutRounding(Visual visual)
    {
        if (visual is UIElement)
            (visual as UIElement).SetValue(UseLayoutRoundingProperty, true);   

        for (var i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
        {
            var child = VisualTreeHelper.GetChild(visual, i);
            if(child is Visual)
                SetLayoutRounding((Visual)child);
        }
    }
Marcel