假设我们有
<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; }
}
问题是尽管设置了回退值,但我仍然收到绑定错误事件:
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,因此我们确实需要某种方法来抑制这些绑定错误,因为它们会影响性能。
在我的项目中,我们在创建视图后使用 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/