33

我有一个绑定TextBlock的 XAML:

<TextBlock Text="{Binding MyText}"/>

我知道FallbackValue如果绑定不可用,可以使用,但这发生在运行时?有没有办法在设计时显示默认值?如果我在设计窗口时能看到一个值而不是一个空的TextBlock.

谢谢

4

4 回答 4

56

更新:Visual Studio 2019 v16.7

您现在可以执行以下操作:

<TextBlock Text="{Binding MyText}" d:Text="Design time value"/>

如果您更喜欢Ian Bamforth 的答案的不那么冗长的版本,您可以这样做

<TextBlock Text="{Binding MyText, FallbackValue=None}"/>
于 2013-06-25T13:45:05.043 回答
8

从这个问题改编一个例子。

这对我有用 - 设计器中显示文本“无”:

 <TextBlock>
    <TextBlock.Text>
        <Binding ElementName="root" Path="blah" FallbackValue="None" />
    </TextBlock.Text>
</TextBlock>

希望有帮助

于 2013-06-20T08:29:28.160 回答
6

使用FallbackValue是错误的,因为它还会影响运行时行为(如果绑定无法从源获取值,则使用回退值)。

我想出了一个模仿的自定义标记扩展Binding(理想情况下,我宁愿继承自Binding,但该ProvideValue方法不是虚拟的......):

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);
        }
    }
}

您可以像 一样使用它Binding,并添加以下DesignValue属性:

<TextBlock Text="{my:BindingEx Name, DesignValue=John Doe}" />

请注意,BindingEx它不具有 中的所有属性Binding,但您可以在必要时轻松添加它们。

于 2020-01-07T14:22:17.540 回答
1

如果您绑定了此数据并且正在使用 MVVM 架构,那么为它绑定的模型项设置一个 DEFAULT 值将在设计时显示该值

我只是在使用:

模型.cs:

private int frame = 999999;
public int Frame
{
  get { return frame; }
  set
  {
    frame = value;
    NotifyPropertyChanged(m => m.Frame);
  }
}

在我的 XAML 中:

 <TextBlock Text="{Binding Path=Frame}"  />

并且“999999”的默认值正在设计器中显示

于 2015-01-05T13:19:22.360 回答