简体   繁体   English

当源对象可能没有给定属性时如何处理绑定?

[英]How to handle bindings when the source object may not have the given property?

I have two classes with different properties, but both inherit some other base class: 我有两个具有不同属性的类,但都继承了其他一些基类:

public class BaseClass { }

public class ClassA : BaseClass
{
    public string PropertyA { get; set; }
}

public class ClassB : BaseClass
{
    public string PropertyB { get; set; }
}

Code-behind: 代码隐藏:

public ObservableCollection<BaseClass> Items { get; set; }

public MainWindow()
{
    Items = new ObservableCollection<BaseClass>
        {
            new ClassA {PropertyA = "A"},
            new ClassB {PropertyB = "B"}
        };
}

And my XAML looks like this: 我的XAML看起来像这样:

<ListView ItemsSource="{Binding Items}">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding PropertyA, FallbackValue=''}"/>
            <GridViewColumn DisplayMemberBinding="{Binding PropertyB, FallbackValue={x:Null}}"/>
        </GridView>
    </ListView.View>
</ListView>

When running in debug mode, the output window shows this: 在调试模式下运行时,输出窗口显示:

System.Windows.Data Warning: 40 : BindingExpression path error: 'PropertyB' property not found on 'object' ''ClassA' (HashCode=66437409)'. System.Windows.Data警告:40:BindingExpression路径错误:'object'''ClassA'(HashCode = 66437409)'上找不到'PropertyB'属性。 BindingExpression:Path=PropertyB; BindingExpression:路径= PropertyB; DataItem='ClassA' (HashCode=66437409); DataItem ='ClassA'(HashCode = 66437409); target element is 'TextBlock' (Name=''); target元素是'TextBlock'(Name =''); target property is 'Text' (type 'String') target属性是'Text'(类型'String')

System.Windows.Data Warning: 40 : BindingExpression path error: 'PropertyA' property not found on 'object' ''ClassB' (HashCode=2764078)'. System.Windows.Data警告:40:BindingExpression路径错误:'对象'''ClassB'(HashCode = 2764078)'上找不到'PropertyA'属性。 BindingExpression:Path=PropertyA; BindingExpression:路径= PropertyA; DataItem='ClassB' (HashCode=2764078); DataItem ='ClassB'(HashCode = 2764078); target element is 'TextBlock' (Name=''); target元素是'TextBlock'(Name =''); target property is 'Text' (type 'String') target属性是'Text'(类型'String')

Is there a better way of handling bindings like these? 有没有更好的方法来处理像这样的绑定? Are there any performance implications, and is it better to use FallbackValue='' or FallbackValue={x:Null}? 是否有任何性能影响,使用FallbackValue =''或FallbackValue = {x:Null}是否更好?

Personally I just ignore them. 就个人而言,我只是忽略它们。 If an item doesn't exist, it gets displayed as an empty string, which is usually what I prefer. 如果某个项目不存在,它将显示为空字符串,这通常是我喜欢的。

They are warnings in the debug window because they are simply warnings, not errors. 它们是调试窗口中的警告,因为它们只是警告,而不是错误。 They're warning you of a possible problem, but nothing bad will happen if you ignore them. 他们会警告你一个可能存在的问题,但是如果忽略它们就不会发生任何不好的事情。

If it really bothers you, you can probably use a Template Column and specify different DataTemplates for the different object types. 如果它真的困扰你,你可以使用模板列并为不同的对象类型指定不同的DataTemplates。

<DataTemplate TargetType="{x:Type local:ClassA}">
    <TextBlock Text="{Binding PropertyA}" />
</DataTemplate>

<DataTemplate TargetType="{x:Type local:ClassB}">
    <TextBlock Text="{Binding PropertyB}" />
</DataTemplate>

I will also sometimes use a Converter which returns typeof(value) , and use that type in a DataTrigger 我有时也会使用返回typeof(value)的Converter,并在DataTrigger中使用该类型

<Style.Triggers>
    <DataTrigger Value="{x:Type local:ClassA}" 
                 Binding="{Binding Converter={StaticResource ObjectToTypeConverter}}">
        <Setter Property="Text" Value="{Binding PropertyA}" />
    </DataTrigger>
    <DataTrigger Value="{x:Type local:ClassB}" 
                 Binding="{Binding Converter={StaticResource ObjectToTypeConverter}}">
        <Setter Property="Text" Value="{Binding PropertyB}" />
    </DataTrigger>
</Style.Triggers>

Easy option to eliminate this warning is to use PriorityBinding as mentioned by @snurre like this: 消除这种警告容易的选择是使用PriorityBinding由@snurre这样提到:

<GridViewColumn.DisplayMemberBinding>
    <PriorityBinding>
        <Binding Path="PropB" />
    </PriorityBinding>
</GridViewColumn.DisplayMemberBinding>

Warning will not appear for missing PropB property. 错过的PropB属性不会出现警告。

I would prefer following way: 我更喜欢以下方式:

Write a custom value converter implementing IMultiValueConverter . 编写实现IMultiValueConverter的自定义值转换器。 In this converter you can check the incoming values, choose the valid one and give that value back. 在此转换器中,您可以检查传入值,选择有效值并返回该值。

In Xaml add a MultiBinding like that: 在Xaml中添加一个MultiBinding,如下所示:

<MultiBinding Converter="{StaticResource ResourceKey=myMultiValueConverter}" ConverterParameter="SomeParameterIfNecessary">
    <Binding "ToTheFirstClass.PropertyA" />
    <Binding "ToTheSecondClass.PropertyB" />
</MultiBinding>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WPF中的Bindings属性更改更改如何使Button做出反应? - How to have the Button react on the Bindings Property Change change in WPF? 设置对象时如何保持绑定? - How to maintain bindings when setting object? LINQ:当对象可能为null时,一种更好的选择属性的方法吗? - LINQ: A better way to select a property when the object may be null? 如何序列化 object 但给定属性仍序列化为字节数组? - How can I serialize an object but have a given property remain serialized to a byte array? 尝试写入事件日志时出错 - 无法打开源“SourceName”的日志。 您可能没有写入权限 - Error when attempting to write to event log - Cannot open log for source 'SourceName'. You may not have write access 如何在未实现 INotifyPropertyChanged 的​​对象时更新绑定。 WPF - How to Update bindings when an object with no INotifyPropertyChanged implemented. WPF 更改端点时客户端和服务绑定可能不匹配 - The Client And Service Bindings May Be Mismatched When Changing Endpoint 在c#Web Api中反序列化JSON对象时如何绑定给定的属性? - How to bind a given property when deserializing a JSON object in c# Web Api? 使用 object 初始化程序语法时,“在构造函数和初始化程序中,仅支持属性或字段参数绑定” - “In constructors and initializers, only property or field parameter bindings are supported” when using object initializer syntax 当源对象没有继承关系时,如何使用 AutoMapper 包含子对象映射? - How can I include a child object mapping using AutoMapper when the source objects have no inheritance relationship?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM