【问题标题】:Editing a textbox using multi binding使用多重绑定编辑文本框
【发布时间】:2015-09-07 21:57:35
【问题描述】:

我有一个使用多重绑定的文本框。用于此多重绑定的字段是来自我的数据视图模型的属性

<TextBox>
    <TextBox.Text>
        <MultiBinding StringFormat="{}{0} {1}">
            <Binding Path="FirstProperty" />
            <Binding Path="SecondProperty" />
        </MultiBinding>
    </TextBox.Text>
</TextBox>

我希望在允许用户更新内容的同时保持这种行为;然后我会在我的数据视图模型中检索文本框的内容。

有可能吗?

【问题讨论】:

标签: c# wpf mvvm multibinding


【解决方案1】:

虽然 pangabiMC 指向的链接使用了我个人不会使用的转换器,但如果您将此行为放在视图模型中,则调试和单元测试都会更容易。只需为您的文本框创建一个单独的属性 (CombinedProperty) 并使其与原始属性保持同步:

public class YourViewModel : ViewModelBase
{
    private string _FirstProperty = "";
    public string FirstProperty
    {
        get { return this._FirstProperty; }
        set
        {
            this._FirstProperty = value;
            RaisePropertyChanged(() => this.FirstProperty);
            UpdateCombinedProperty();
        }
    }

    private string _SecondProperty = "";
    public string SecondProperty
    {
        get { return this._SecondProperty; }
        set
        {
            this._SecondProperty = value;
            RaisePropertyChanged(() => this.SecondProperty);
            UpdateCombinedProperty();
        }
    }

    private string _CombinedProperty = "";
    public string CombinedProperty
    {
        get { return this._CombinedProperty; }
        set
        {
            this._CombinedProperty = value;
            RaisePropertyChanged(() => this.CombinedProperty);
            UpdateSourceProperties();
        }
    }

    private void UpdateCombinedProperty()
    {
        this.CombinedProperty = this.FirstProperty + " " + this.SecondProperty;
    }

    private void UpdateSourceProperties()
    {
        var fields = this.CombinedProperty.Split(' ');
        if (fields.Length != 2)
            return; // should handle validation properly
        this.FirstProperty = fields[0];
        this.SecondProperty = fields[1];
    }

}

【讨论】:

  • 嘿,马克,我继续谦虚地编辑了您的回复,这对我来说效果很好。感谢您加入团队。
  • @Louitbol 您的编辑在审核队列中,但由于您除了更正实际错误之外还更改了其他代码,因此它可能无法通过。 (可能是因为编辑长度要求?)如果被拒绝,只需注释必要的更改,以便 Mark 可以修复它。
  • @GalacticCowboy 我相信这是因为我第一次编辑时没有登录。
  • 好吧,我的编辑一直被拒绝,不知道为什么这个代码会抛出 SOE。哦,好吧...
  • 奇怪,不是为我做的。您的编辑是否仅包括检查值是否与当前值不同?
猜你喜欢
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多