将NULL值显示为“NULL”的最简单方法是什么?使用WPF数据绑定? [英] What's the simplest way to display NULL values as "NULL" with WPF Data Binding?

查看:367
本文介绍了将NULL值显示为“NULL”的最简单方法是什么?使用WPF数据绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个遗留数据库,我正在使用Linq到Sql构建一个自定义查看器。



现在表中的一些字段可以具有NULL值。
在DataTemplate中使用正常的数据绑定(为ORM Designer生成的类输入)

 < TextBlock Text = {Binding Path = columnX}/> 

如果columnX的值为NULL,则不显示任何内容。 (似乎是WPF约定)如果值为NULL,我想显示NULL。 (相当于 column_value ??NULL



我可以使用转换器,如

 < TextBlock Text ={Binding Path = columnX,Converter = {StaticResource nullValueConverter}}/> 

转换器类

 code> class NullValueConverter:IValueConverter 
{
public object Convert(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture)
{
if(value == null)
返回NULL;
...

但这似乎太多的工作。此外,这个逻辑需要在现有的非平凡转换器中重复。



有没有快速的方法来实现这一点?

解决方案

绑定类有一个名为 TargetNullValue 的属性,可用于替换其他内容,如果绑定返回NULL值。您的示例变成: -

 < TextBlock Text ={Binding Path = columnX,TargetNullValue = My Substitute Text}/> ; 

Binding类的另一个属性也可用于称为 FallbackValue 。如果绑定表达式无法解析(即未找到),例如,当您使用的路径(示例中的columnX)不是数据上下文或源的成员时,这将是替代值。



更新(Gishu):需要 。NET Framework 3.5 SP1 一个53MB的下载。没有它,上面的代码将不会编译。 TargetNullValue是Binding类的新添加。


I have this legacy database for which I'm building a custom viewer using Linq to Sql.

Now some of the fields in a table can have the value NULL. Using normal databinding in a DataTemplate (typed for the Class generated by the ORM Designer)

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

If columnX has value NULL, nothing is displayed. (It seems the to be the WPF convention) I'd like to display "NULL" instead if the value is NULL. (equivalent to column_value ?? "NULL")

I could use a converter as in

<TextBlock Text="{Binding Path=columnX, Converter={StaticResource nullValueConverter}}"/>

Converter class

class NullValueConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    if (value == null)
      return "NULL";
    ...

But this seems like too much work. Also this logic would need to be duplicated in existing non-trivial converters..

Is there a quick-hit way to accomplish this?

解决方案

The binding class has a property called TargetNullValue that can be used to substitute something else if the binding returns a NULL value. Your example becomes:-

<TextBlock Text="{Binding Path=columnX, TargetNullValue=My Substitute Text}"/>

There is another property of the Binding class that is also useful called FallbackValue. This would be the substitute value to use if the binding expression cannot be resolved (i.e. not found), e.g for when the path you use (columnX in your example) is not a member of the data context or source.

Update(Gishu): Requires .NET Framework 3.5 SP1 a 53MB download. Without it, the above code won't compile. TargetNullValue is a new addition to the Binding class.

这篇关于将NULL值显示为“NULL”的最简单方法是什么?使用WPF数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆