c# - 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}}
为什么显示这个而不是显示为空?有什么办法可以将其显示为空吗?
解决方案
这应该可以解决问题:
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
值,因为它们不是。StringFormat
PlaceHolder
DependencyProperty
推荐阅读
- ios - 当我打开我的 iOS 应用程序时,屏幕变黑。为什么?
- swift - 将子视图添加到视图控制器时,SKScene 不会出现
- java - 如何加入仅获取选定的子实体与父实体
- ios - 在 Xcode 11.4/iOS 13.4 我发现 NSUserActivity 并不总是响应 setSuggestedInvocationPhrase
- c# - CSV Helper:解析空单元格与空单元格
- python - 列表中元素的概率
- javascript - 如何使用左右渲染的一堆瓷砖来渲染无缝平铺精灵
- python - Keras - 预计密集有形状
- javascript - React-Redux:如果用户未登录,则限制用户访问某些页面的最佳方法
- javascript - 基于类名的jQuery排序不起作用