如何在对象类型的依赖项属性上绑定MultiBinding

时间:2012-02-09 02:47:46

标签: c# .net wpf data-binding attached-properties

我有以下绑定

<Display.Value>
    <MultiBinding StringFormat="{}{0} ({1})">
          <Binding Path="Nickname" />
          <Binding Path="FullName"  />
    </MultiBinding>
</Display.Value>

根据MultiBinding class documentation,这是正确的语法。但是,当我将它绑定到value属性时,只显示一个空字符串。但是,当我使用SingleBinding或仅使用普通Binding时,此属性可用。

public object Value
{
    get { return (object)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(object), typeof(Display), new PropertyMetadata(String.Empty));

但是,当我在另一个附加属性上绑定我的多重绑定时(这次,类型是字符串)

    public string Caption
    {
        get { return (string)GetValue(CaptionProperty); }
        set { SetValue(CaptionProperty, value); }
    }

    public static readonly DependencyProperty CaptionProperty =
        DependencyProperty.Register("Caption", typeof(string), typeof(Display), new PropertyMetadata(String.Empty));

任何想法为什么多重绑定不适用于Value但适用于Caption?是因为Value的对象类型?如何使MultiBinding与Value一起使用?

2 个答案:

答案 0 :(得分:0)

这对我有用:

XAML

<Window ....
    DataContext="{Binding RelativeSource={RelativeSource Self}}">

    <Grid>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{}{0} - ({1})">
                    <Binding Path="Value.Nickname"/>
                    <Binding Path="Value.FullName"/>
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </Grid>
</Window>

代码隐藏

public class Value
{
    public static readonly DependencyProperty NicknameProperty =
       DependencyProperty.Register("Nickname", typeof(string), typeof(Value), new PropertyMetadata(string.Empty));

    public string Nickname
    {
        get { return (string)GetValue(NicknameProperty); }
        set { SetValue(NicknameProperty, value); }
    }

    public static readonly DependencyProperty FullNameProperty =
       DependencyProperty.Register("FullName", typeof(string), typeof(Value), new PropertyMetadata(string.Empty));

    public string FullName
    {
        get { return (string)GetValue(FullNameProperty); }
        set { SetValue(FullNameProperty, value); }
    }

    public Value()
    {
        Nickname = "Nickname";
        FullName = "FullName";
    }
}


所以聊天之后最好在处理非字符串时使用Converter。使用StringFormat将使用字符串。

答案 1 :(得分:0)

MultiBinding知道目标属性的类型,如果它不是string类型,你应该得到这个binding error

  

System.Windows.Data错误:31:无法设置MultiBinding,因为必须指定MultiValueConverter。 MultiBinding: 'System.Windows.Data.MultiBinding'

您可以将TextBlock分配给ValueText通过MultiBinding绑定,或者您当然可以使用转换器。

相关问题