1

2 つのバインディングを一緒に「追加」して、それらにいくつかの文字列を追加する方法はありますか? これを説明するのは非常に難しいですが、たとえば次のように、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");
        }
    }
}

役立つかもしれない別のアプローチは、コンバーターを使用することです。ただし、この場合、 とが同じオブジェクトのプロパティであるFNと仮定します。LN

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 に答える