首页 > 解决方案 > WPF 标签内容在设计模式下显示 DependencyProperty.UnsetValue

问题描述

我有一个 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}}

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

标签: c#wpflabelwpf-controls

解决方案


这应该可以解决问题:

 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>

请注意,您只能在and - 中设置static值,因为它们不是。StringFormatPlaceHolderDependencyProperty


推荐阅读