Reputation: 5627
I have a binded TextBlock
, XAML:
<TextBlock Text="{Binding MyText}"/>
I know the FallbackValue
can be used if the Binding isn't available, but this happens at run time ? Is there any way to show a default value at design time ? It would make things easier if I could see a value when designing my windows instead of an empty TextBlock
.
Thanks
Upvotes: 37
Views: 18923
Reputation: 3589
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}"/>
Upvotes: 67
Reputation: 292555
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.
Upvotes: 7
Reputation: 19
If you have this data bound and are using the MVVM architecture then setting a DEFAULT value for the model item it is bound to will display the value at design time
I am just using:
Model.cs:
private int frame = 999999;
public int Frame
{
get { return frame; }
set
{
frame = value;
NotifyPropertyChanged(m => m.Frame);
}
}
and in my XAML:
<TextBlock Text="{Binding Path=Frame}" />
and the default value of "999999" is being displayed in the designer
Upvotes: 1