我有一個包含3個項目的下拉列表。我想要做的是如果我選擇一個特定的項目,我需要評估一個規則,如果規則建議選擇一個不同的項目,我需要選擇它而不是用戶選擇的項目。更新設置器中的值未在控件中刷新
例如我有3個項目「ABC」,「DEF」&「GHI」。如果用戶試圖選擇「ABC」,那麼我需要選擇「DEF」。我從選定項目屬性的setter中完成此操作,但出於某種奇怪的原因,它沒有更新。我知道.NET 3.5中存在類似的問題,並已在.NET 4.0中解決,但我使用.NET 4.0,在我的情況下,它仍然存在。請你能建議如何解決這個問題?
代碼:
視圖模型:
public class ViewModel
{
public ViewModel()
{
AllItems = new List<string> { "ABC", "DEF", "GHI" };
}
private List<string> _itemsList;
public List<string> AllItems
{
get { return _itemsList; }
set
{
_itemsList = value;
OnPropertyChanged("AllItems");
}
}
private string _selectedItem;
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = ValidateRules(value);
OnPropertyChanged("SelectedItem");
}
}
public string ValidateRules(string selection)
{
if (selection == "ABC")
return "DEF";
return selection;
}
}
查看:
<Grid>
<ComboBox ItemsSource="{Binding AllItems}" SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200"/>
</Grid>
嘗試用if(selection.Equals(「ABC」))替換if(選擇==「ABC」)) – metacircle
@metacircle:它們基本上是相同的東西;字符串類覆蓋相等運算符並檢查字符串內容匹配(即不使用引用等於)。 string == string與String.Equals完全相同 – Jeb
嘗試綁定到SelectedValue而不是SelectedItem。 –