优雅地处理预期的 BindingExpression 错误

Gracefully handling expected BindingExpression errors

我有一个 ComboBox 绑定到一个 ObservableCollection,其中 DisplayMemberPath 引用一个对象 属性 Url.

我的 CompositeCollection 包含一个 null 项目,允许用户有一个可选的选择:

<ComboBox Grid.Row="7" Grid.Column="1" Height="24" VerticalAlignment="Top"
          IsSynchronizedWithCurrentItem="True"
          SelectedItem="{Binding SelectedNotificationServer, Mode=TwoWay}"
          DisplayMemberPath="Url">
    <ComboBox.Resources>
        <CollectionViewSource x:Key="comboBoxSource" Source="{Binding Path=NotificationServers}" />
    </ComboBox.Resources>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Content="None"/>
            <CollectionContainer Collection="{Binding Source={StaticResource comboBoxSource}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

这工作正常(它产生一个 URL 下拉列表和一个默认的 "None" 项目),但是在调试时,我有一个错误,因为 Url 属性 在null 项:

System.Windows.Data Error: 40 : BindingExpression path error: 'Url' property not found on 'object' ''ComboBoxItem' (Name='')'. BindingExpression:Path=Url; DataItem='ComboBoxItem' (Name=''); target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

我该如何优雅地处理这个问题,即使它不会导致任何运行时问题。这可能只是调试噪音,但仍然很麻烦。

您的 'null' 项目应该只是您的 collection 中的一个项目(与其他项目类型相同)没有设置属性,或者至少没有显示属性.这样,您就可以一起避免 Binding 错误,因为您的 'null' 项 具有 Url 属性 数据绑定到.


更新>>>

您可以在访问其他数据项时像这样设置 'null' 项:

NotificationServers.Add(new NotificationServer());
NotificationServers.AddRange(GetNotificationServers());

这将使它成为第一项。你也可以这样做:

NotificationServers.Add(new NotificationServer() { DisplayedProperty = "Please Select" });