How can I have ifdefs in XAML
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 W开发者_运维问答PF4
set property
#endif
}
Is there an elegant way to accomplish the same thing in XAML?
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}"/>
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);
}
}
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.
精彩评论