我有一个使用多重绑定的文本框。用于此多重绑定的字段是来自我的数据视图模型的属性
<TextBox>
<TextBox.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="FirstProperty" />
<Binding Path="SecondProperty" />
</MultiBinding>
</TextBox.Text>
</TextBox>
我想在允许用户更新内容的同时保持这种行为;然后,我将在数据视图模型中检索文本框的内容。
有可能吗?
答案 0 :(得分: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];
}
}