Edw*_*uay 1 c# data-binding wpf mvvm
在我的视图中,我有一个滑块和一个组合框.
当我更改滑块时,我希望组合框改变.
当我更改组合框时,我想要更改滑块.
我可以使用其中一个,但如果我尝试更新两个,我会收到StackOverflow错误,因为一个属性在无限循环中不断更新另一个属性.
我已经尝试进入一个Recalculate(),其中更新在一个地方完成,但仍然遇到递归问题.
如何在不进行递归的情况下让每个控件更新另一个?
在视图中:
<ComboBox
ItemsSource="{Binding Customers}"
ItemTemplate="{StaticResource CustomerComboBoxTemplate}"
Margin="20"
HorizontalAlignment="Left"
SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"/>
<Slider Minimum="0"
Maximum="{Binding HighestCustomerIndex, Mode=TwoWay}"
Value="{Binding SelectedCustomerIndex, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)
在ViewModel中:
#region ViewModelProperty: SelectedCustomer
private Customer _selectedCustomer;
public Customer SelectedCustomer
{
get
{
return _selectedCustomer;
}
set
{
_selectedCustomer = value;
OnPropertyChanged("SelectedCustomer");
SelectedCustomerIndex = _customers.IndexOf(_selectedCustomer);
}
}
#endregion
#region ViewModelProperty: SelectedCustomerIndex
private int _selectedCustomerIndex;
public int SelectedCustomerIndex
{
get
{
return _selectedCustomerIndex;
}
set
{
_selectedCustomerIndex = value;
OnPropertyChanged("SelectedCustomerIndex");
SelectedCustomer = _customers[_selectedCustomerIndex];
}
}
#endregion
Run Code Online (Sandbox Code Playgroud)
尝试设置函数类似于:
public int SelectedCustomerIndex
{
get
{
return _selectedCustomerIndex;
}
set
{
if (value != _selectedCustomerIndex)
{
_selectedCustomerIndex = value;
OnPropertyChanged("SelectedCustomerIndex");
SelectedCustomer = _customers[_selectedCustomerIndex];
}
}
}
Run Code Online (Sandbox Code Playgroud)
仅在值发生实际变化时触发事件.这样,第二次调用具有相同值的set属性不会导致另一个更改事件.
当然,你必须为其他财产这样做.