等等合并()在XAML绑定? [英] Equiv. to Coalesce() in XAML Binding?

查看:202
本文介绍了等等合并()在XAML绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL中,我可以这样做:

In SQL I can do this:

Select Coalesce(Property1, Property2, Property3, 'All Null') as Value
From MyTable 

如果Property1,2和3都为空,那么我得到'全部Null'

If Property1, 2 and 3 are all null, then I get 'All Null'

如何在XAML中执行此操作?我试过以下,但没有运气:

How do I do this in XAML? I tried the following, but no luck:

<Window.Resources>
    <local:Item x:Key="MyData" 
                Property1="{x:Null}"
                Property2="{x:Null}"
                Property3="Hello World" />
</Window.Resources>

<TextBlock DataContext="{StaticResource MyData}">
    <TextBlock.Text>
        <PriorityBinding TargetNullValue="All Null">
            <Binding Path="Property1" />
            <Binding Path="Property2" />
            <Binding Path="Property3" />
        </PriorityBinding>
    </TextBlock.Text>
</TextBlock>

结果应该是Hello World,而是All Null

The result should be 'Hello World' but instead it is 'All Null'

我希望我的问题很清楚。

I hope my question is clear.

推荐答案

你必须建立一个自定义 IMultiValueConverter 执行此操作并使用MultiBinding。 PriorityBinding 使用集合中的第一个绑定成功生成一个值。在你的情况下,Property1绑定立即解析,所以它被使用。由于Property1为null,因此使用了TargetNullValue。

You'd have to build a custom IMultiValueConverter to do that and use a MultiBinding. PriorityBinding uses the first binding in the collection that produces a value successfully. In your case, the Property1 binding resolves immediately, so it's used. Since Property1 is null, the TargetNullValue is used.

这样的转换器:

public class CoalesceConverter : System.Windows.Data.IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, 
            object parameter, System.Globalization.CultureInfo culture)
    {
        if (values == null)
            return null;
        foreach (var item in values)
            if (item != null)
                return item;
        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, 
            object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

和MultiBinding这样:

And MultiBinding like this:

<Window.Resources>
    <local:Item x:Key="MyData" 
                Property1="{x:Null}"
                Property2="{x:Null}"
                Property3="Hello World" />
    <local:CoalesceConverter x:Key="MyConverter" />
</Window.Resources>

<TextBlock DataContext="{StaticResource MyData}">
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource MyConverter}">
            <Binding Path="Property1" />
            <Binding Path="Property2" />
            <Binding Path="Property3" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

这篇关于等等合并()在XAML绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆