gpt4 book ai didi

c# - 更新 ViewModel 属性时如何避免递归?

转载 作者:太空宇宙 更新时间:2023-11-03 18:49:57 25 4
gpt4 key购买 nike

在我的 View 中,我有一个 slider 和一个组合框

当我更改 slider 时,我希望组合框也随之更改。

当我更改组合框时,我希望 slider 发生变化。

我可以更新一个或另一个,但如果我尝试更新两者,我会收到一个StackOverflow 错误,因为一个属性在无限循环中不断更新另一个。

我已经尝试放入一个 Recalculate() ,其中更新在一个地方完成,但仍然遇到递归问题。

如何在不进入递归的情况下让每个控件更新另一个控件?

在 View 中:

<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}"/>

在 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

最佳答案

在集合函数中尝试类似这样的东西:

public int SelectedCustomerIndex
{
get
{
return _selectedCustomerIndex;
}

set
{
if (value != _selectedCustomerIndex)
{
_selectedCustomerIndex = value;
OnPropertyChanged("SelectedCustomerIndex");
SelectedCustomer = _customers[_selectedCustomerIndex];
}
}
}

仅当值发生实际变化时才触发事件。这样,第二次调用具有相同值的 set 属性不会导致另一个更改事件。

当然,您也必须为其他属性执行此操作。

关于c# - 更新 ViewModel 属性时如何避免递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1012812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com