1

有没有一种方法可以将两个绑定“添加”在一起并向它们添加一些字符串?这很难解释,但可以在 XAML 代码中绑定到 TextBlock,例如:

<TextBlock Name="FirstName" Text="{Binding FN}" />

我想做的是:

<TextBlock Name="FirstLastName" Text="{Binding FN} + ', ' + {Binding LN}" />

所以本质上你会得到这样的东西:

院长,格罗布勒

提前致谢!

4

1 回答 1

3

首先想到的是创建VM包含连接值的附加属性:

public string FullName
{
    get { return FN + ", "+ LN; }
}

public string FN
{
    get { return _fN; }
    set 
    {
        if(_fn != value)
        {
            _fn = value;
            FirePropertyChanged("FN");
            FirePropertyChanged("FullName");
        }
    }

}

public string LN
{
    get { return _lN; }
    set
    {
        if(_lN != value)
        {
            _lN = value;
            FirePropertyChanged("LN");
            FirePropertyChanged("FullName");
        }
    }
}

另一种可能有帮助的方法是使用转换器。但在这种情况下,我们假设FNLN是同一对象的属性:

public class PersonFullNameConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!(value is Person)) throw new NotSupportedException();
        Person b = value as Person;
        return b.FN + ", " + b.LN;
    }

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

public class Person
{
    public string FN { get; set; }
    public string LN { get; set; }
}

VM

public Person User
{
    get { return _user; }
    set
    {
        if(_user != value)
        {
            _user = value;
            FirePropertyChanged("User");            
        }
    }
}
于 2012-10-10T08:34:45.157 回答