使用TwoWay将string []绑定到XAML

时间:2015-11-04 16:41:55

标签: c# wpf mvvm data-binding

我有一个模型,我收到一个名为birth的属性,格式为

birthday, birthplace

我已将其设置在Model

private string _birth;
/// <summary>
/// Birth information in format: birthday, birthplace
/// </summary>
[Column("birth")]
[JsonProperty("birth")]
public string Birth
{
    get { return this._birth; }
    set
    {
        this._birth= value;
        OnPropertyChanged();
        OnPropertyChanged("BirthData");
    }
}

我也设置了这样的公开modifier

    /// <summary>
    /// Split the birth data if exists
    /// </summary>
    public string[] BirthData
    {
        get { return this.Birth?.Split(',');  }
    }

在我的XAML文件中,我为我的模型正确设置了一切,除了我无法理解如何在这样的事情上使用TwoWay绑定。您可以在下面找到此特定属性的XAML摘录

<Label x:Name="BirthdayLabel" Content="Nato Il" />
<DatePicker x:Name="BirthdayDateTimePicker" SelectedDate="{Binding selectedModel.BirthData[0], Mode=TwoWay}"></DatePicker>
<Label x:Name="BirthplaceLabel" Content="Nato A"/>
<TextBox x:Name="BirthplaceTextBox" Text="{Binding selectedModel.BirthData[1], Mode=TwoWay}"/>

当然这不能正常工作,因为即使绑定按预期工作,我最终会使用有关属性的旧信息selectedModel,我认为TwoWay绑定不适用于数组这样的数据。

我无法更改DataSource,而且我要找到一种方法来使用一个文本框和一个日期选择器并在我的ViewModel中一起使用,除了一个名为Update()的单个方法之外没有太多的方法。当前selectedModel。

1 个答案:

答案 0 :(得分:2)

ViewModel是关于为View构建数据

因此,我建议您在视图模型中拆分并解析数据,并为BirthDateBirthPlace公开两个属性:

class Person
{
    private string _birth;
    public string Birth{
        get { return this._birth; }
        set
        {
            this._birth = value;
            SplitBirthIntoBirthDayAndBirthPlace();
            OnPropertyChanged();
        }
    }
    private DateTime _birthday;
    public DateTime Birthday{
        get { return _birthday; }
        set
        {
            _birthday = value;
            ReComputeBirth();
            OnPropertyChanged();
        }
    }
    // Same for Birthplace ...
    private void ReComputeBirth(){
        // ... Format the data as expected ...
        _birth = _birthday + ", " + _birthplace;
    }
    private void SplitBirthIntoBirthDayAndBirthPlace()
    {
        String[] values = _birth.Split(',', ' ');
        // ... really make the parse here to fill _birthplace and _birthdate...
    }
    // ....
}

绑定更简单:

    <DatePicker x:Name="BirthdayDateTimePicker"
                SelectedDate="{Binding selectedModel.Birthday, Mode=TwoWay}"/>

    <TextBox x:Name="BirthplaceTextBox"
             Text="{Binding selectedModel.Birthplace, Mode=TwoWay}"/>
相关问题