WPF标签内容在设计模式下显示DependencyProperty.UnsetValue

时间:2018-06-29 14:26:48

标签: c# wpf label wpf-controls

我有一个WPF标签,并且已使用xaml中的StringFormat将一些数据绑定到字符串中:

<Label Grid.Row="0" Grid.Column="1" Style="{StaticResource MyLblResource}">
    <Label.Content>
        <TextBlock VerticalAlignment="Center">
            <TextBlock.Text>
                <MultiBinding StringFormat="{}({0}) {1}">
                    <Binding Path="MyDataModel.Id" />
                    <Binding Path="MyDataModel.Desc" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </Label.Content>
</Label>

上面的代码工作正常,没有问题,但是在设计时,在xaml视图中,在TextBlock内容中显示:

{{DependecyProperty.UnsetValue}} {{DependencyProperty.UnsetValue}}

为什么这样显示而不是显示为空?有什么办法可以显示为空吗?

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

 public class StringFormatConverter : MarkupExtension, IMultiValueConverter
    {
        public string StringFormat { get; set; } = @"({0}) {1}";

        public string PlaceHolder { get; set; } = "Empty";

        public override object ProvideValue(IServiceProvider serviceProvider) => this;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            return string.Format(StringFormat, GetValues(values));
        }

        private IEnumerable<string> GetValues(object[] values)
        {
            foreach (var value in values)
                yield return value == DependencyProperty.UnsetValue || value == null ? PlaceHolder : value.ToString();
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return new[] { Binding.DoNothing, Binding.DoNothing };
        }
    }

像这样使用它:

 <MultiBinding Converter="{converter:StringFormatConverter PlaceHolder=MyPlaceHolderText}">
   <Binding Path="MyDataModel.Id" />
   <Binding Path="MyDataModel.Desc" />
</MultiBinding>

请注意,您只能在staticStringFormat中设置PlaceHolder的值-因为它们不是DependencyProperty