Search code examples
c#wpfmvvmmultibinding

Editing a textbox using multi binding


I have a textbox using multi binding. The fields used for this multi binding are properties coming from my data view model

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

I would like to keep this behavior while allowing the user to update the content; I would then retrieve the content of the textbox in my data view model.

Is it possible?


Solution

  • While the link that pangabiMC points to uses a converter I personally wouldn't myself, it's easier to both debug and unit test if you put this behaviour in the view model. Just create a separate property for your textbox (CombinedProperty) and keep it synced to the original properties:

    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];
        }
    
    }