我的ViewModel中有两个属性:
public double Start { get; set; }
public double Duration { get; set; }
我的视图中有三个文本框:
<TextBox Name="StartTextBox" Text="{Binding Start}" />
<TextBox Name="EndTextBox" />
<TextBox Name="DurationTextBox" Text="{Binding Duration} />
我想实现以下行为:
我可以通过在后面的代码中监听TextChanged事件来实现这一点。不过,我宁愿通过MultiBinding实现这一点。有可能吗?
当我尝试使用MultiBinding时遇到的问题:
答案 0 :(得分:1)
我认为打击代码更容易实现您想要的行为:
XAML:
<TextBox Name="StartTextBox" Text="{Binding Start}" />
<TextBox Name="EndTextBox" Text="{Binding End}" />
<TextBox Name="DurationTextBox" Text="{Binding Duration}" />
视图模型:
private double _start;
private double _duration;
private double _end;
public double Start
{
get
{
return _start;
}
set
{
if (_start != value)
{
_start = value;
Duration = _end - _start;
OnPropertyChanged("Start");
}
}
}
public double Duration
{
get
{
return _duration;
}
set
{
if (_duration != value)
{
_duration = value;
End = _duration + _start;
OnPropertyChanged("Duration");
}
}
}
public double End
{
get
{
return _end;
}
set
{
if (_end != value)
{
_end = value;
Duration = _end - _start;
OnPropertyChanged("End");
}
}
}
ViewModel中的OnPropertyChanged实现了这样的INotifyPropertyChanged接口:
public class ViewModelBase:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}