有没有一种方法,当属性路径中有null值导致无法评估绑定时,可以分配一个特殊值?
例如,如果我有一个类Customer中的属性Name和一个像这样的绑定:
{Binding CurrentCustomer.Name}
当 CurrentCustomer 为空时,我希望绑定产生字符串“---”。
“TargetNullValue” 和 “FallbackValue” 看起来无法解决这个问题。
非常感谢您的帮助。
编辑:
实际上,我试图在没有真实值可用时替换一个新的源值。
真正的场景如下:
布尔值用于确定控件的可见性,但当此值不可获取时,我想将其替换为“false”。
以下是完美模拟我的真实用例的示例:
MainPage.xaml.cs :
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace TestSilverlightBindingDefaultValue
{
public class BoolToVisibilityConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
public class Customer
{
public bool HasACar
{
get;
set;
}
}
public partial class MainPage : UserControl
{
public static readonly DependencyProperty CurrentCustomerProperty =
DependencyProperty.Register("CurrentCustomer", typeof(Customer), typeof(MainPage), null);
public Customer CurrentCustomer
{
get { return this.GetValue(CurrentCustomerProperty) as Customer; }
set { this.SetValue(CurrentCustomerProperty, value); }
}
public MainPage()
{
InitializeComponent();
this.CurrentCustomer = null;
this.DataContext = this;
}
}
}
MainPage.xaml:
<UserControl x:Class="TestSilverlightBindingDefaultValue.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:TestSilverlightBindingDefaultValue"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
<local:BoolToVisibilityConverter x:Key="boolToVisibilityConverter" />
</UserControl.Resources>
<StackPanel x:Name="LayoutRoot" Background="White">
<TextBlock Text="You have a car" Visibility="{Binding CurrentCustomer.HasACar,Converter={StaticResource boolToVisibilityConverter}}" />
</StackPanel>
FallbackValue并不是解决方案,因为它只会改变生成的值而不是源值。
Abe Heidebrecht已经为WPF提供了完美的解决方案——PriorityBinding,但在Silverlight中不存在。
最终编辑:Abe Heidebrecht的第二个解决方案,即将内容包裹在另一个元素中,效果非常好。
{x:Null}
。谢谢! - Rachel