仍然使用FallbackValue为复杂属性生成绑定错误

时间:2018-01-24 18:24:05

标签: c# wpf

我们说我们有

<Window x:Class="WpfApplication15.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        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"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <StackPanel>
        <TextBox Text="{Binding MyDataObject.MyNestedProperty, FallbackValue={x:Null}}"/>
    </StackPanel>
</Window>

代码背后:

public partial class MainWindow : Window
{
    public MyDataObject MyDataObject { get; set; }

    public MainWindow()
    {
        InitializeComponent();
    }
}

public class MyDataObject
{
    public string MyNestedProperty { get; set; }
}

问题是虽然设置了FallbackValue,但我仍然收到绑定错误事件:

System.Windows.Data Information: 41 : BindingExpression path error: 'MyNestedProperty' property not found for 'object' because data item is null.  This could happen because the data provider has not produced any data yet. BindingExpression:Path=MyDataObject.MyNestedProperty; DataItem='MainWindow' (Name=''); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=MyDataObject.MyNestedProperty; DataItem='MainWindow' (Name=''); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=MyDataObject.MyNestedProperty; DataItem='MainWindow' (Name=''); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')

我知道问题是MyDataObject == null。但是,在这种情况下,我希望FallbackValue能够抑制绑定错误(与简单属性一样)。

在我的项目中,我们在创建视图后使用set DataContext,因此我们确实需要一些方法来抑制这些绑定错误,因为它们会影响性能。

1 个答案:

答案 0 :(得分:1)

  

在我的项目中,我们在创建视图后使用set DataContext,因此我们确实需要一些方法来抑制这些绑定错误,因为它们会影响性能。

在设置DataContext之后以编程方式创建绑定:

DataContext = ...;
textBox.SetBinding(TextBox.TextProperty, new Binding("MyDataObject.MyNestedProperty") { FallbackValue = null });

FallbackValue和任何其他XAML构造都不会帮助您完成此任务。

从MVVM的角度来看,在视图的代码隐藏中以编程方式创建绑定是完全正确的。某些MVVM库(例如ReactiveUI)甚至鼓励您这样做:https://reactiveui.net/docs/handbook/data-binding/