есть ли способ присвоить специальное значение , когда привязка не может быть оценена из-за нулевое значение в пути к свойству ?
Например, если у меня есть свойство Name в классе Customer и привязка примерно так:
{Binding CurrentCustomer.Name}
Когда CurrentCustomer имеет значение null, я бы хотел, чтобы привязка создавала строку «---».
«TargetNullValue» Реальный сценарий таков:
значение типа bool используется для определения видимости элемента управления, но когда это значение недостижимо, я хотел бы заменить его на «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 .
FINAL EDIT : Второе решение Abe Heidebrecht , то есть перенос другого элемента, работает отлично.