2014-04-30 55 views
0

我有一個包含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> 
+0

嘗試用if(selection.Equals(「ABC」))替換if(選擇==「ABC」)) – metacircle

+1

@metacircle:它們基本上是相同的東西;字符串類覆蓋相等運算符並檢查字符串內容匹配(即不使用引用等於)。 string == string與String.Equals完全相同 – Jeb

+0

嘗試綁定到SelectedValue而不是SelectedItem。 –

回答

1

更改UpdateSourceTrigger來引發LostFocus而不是的PropertyChanged。它會工作。

<ComboBox ItemsSource="{Binding AllItems}" SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=LostFocus}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200"/> 

它會工作。

標記它回答如果它解決您的問題。

+1

是的,它的工作原理。你能解釋一下嗎? – Mike