Default value at design time XAML
Update: Visual Studio 2019 v16.7
You can now do:
<TextBlock Text="{Binding MyText}" d:Text="Design time value"/>
If you would prefer a less verbose version of Ian Bamforth's answer, you can just do
<TextBlock Text="{Binding MyText, FallbackValue=None}"/>
Using FallbackValue
is wrong, because it also affects the runtime behavior (the fallback value is used if the binding fails to obtain a value from the source).
I came up with a custom markup extension that mimics Binding
(ideally I would have preferred to inherit from Binding
, but the ProvideValue
method is not virtual...):
using System;using System.ComponentModel;using System.Windows;using System.Windows.Data;using System.Windows.Markup;namespace MyNamespace{ public class BindingEx : MarkupExtension { private readonly Binding _binding; public BindingEx() { _binding = new Binding(); } public BindingEx(string path) { _binding = new Binding(path); } public PropertyPath Path { get => _binding.Path; set => _binding.Path = value; } public BindingMode Mode { get => _binding.Mode; set => _binding.Mode = value; } public RelativeSource RelativeSource { get => _binding.RelativeSource; set => _binding.RelativeSource = value; } public string ElementName { get => _binding.ElementName; set => _binding.ElementName = value; } public IValueConverter Converter { get => _binding.Converter; set => _binding.Converter = value; } public object DesignValue { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); if (target.TargetObject is DependencyObject d && DesignerProperties.GetIsInDesignMode(d)) return DesignValue; return _binding.ProvideValue(serviceProvider); } }}
You can use it just like Binding
, with the addition of the DesignValue
property:
<TextBlock Text="{my:BindingEx Name, DesignValue=John Doe}" />
Note that BindingEx
doesn't have all the properties from Binding
, but you can easily add them if necessary.