命令

2013-06-12 27 views
0

我有一個ComboBox,看起來像這樣:命令

<ComboBox SelectedValue="{Binding Mode}" SelectedValuePath="Key" ItemsSource="{Binding MyModes}" DisplayMemberPath="Value" > 
        <i:Interaction.Triggers> 
         <i:EventTrigger EventName="SelectionChanged"> 
           <i:InvokeCommandAction Command="{Binding DataContext.SetModeCommand,RelativeSource={RelativeSource AncestorType=UserControl,Mode=FindAncestor}}" IsEnabled="{Binding IsForSet}" CommandParameter="{Binding}" ></i:InvokeCommandAction> 
         </i:EventTrigger> 
        </i:Interaction.Triggers> 
       </ComboBox> 

的SelectedValue和的ItemsSource都綁定到模型中的變量。

和命令:SetModeCommand坐在視圖模型。

我想,在模型改變變量時,命令將無法正常工作,但通過UI改變時,它纔有效。

所以我創建了一個名爲IsForSet(布爾)變量,當我通過模型改變變量Mode我把它錯誤:

IsForSetUM = false; 
Mode = 202; 
IsForSetUM = true; 

我的問題是,該命令不只要我改叫Mode。但只有在我將IsForSetUM更改爲true後。

我有一個解決方案!

我的問題是爲什麼時立即更改了Mode不叫命令?

+0

我不完全知道你正在嘗試做的,但如果你設置了組合框SelectedValue Binding Mode to Mode = TwoWay,那麼對你的Model/ViewModel的改變應該立即反映在UI中(假設你的Model/ViewModel屬性實現了INotifyPropertyChanged)。 –

+0

@RichardE根據OP的描述,您實際上需要'Mode = OneWayToSource'來確保只能從View - > VM/Model – Viv

+0

@Viv進行更改@Viv我不想僅從View中進行更改...我希望命令僅在從View中更改時纔有效。 –

回答

1

解決的辦法是設置在你的綁定到真正NotifyOnSourceUpdated並在EventTrigger使用SourceUpdated事件,像這樣:

<ComboBox SelectedValue="{Binding Mode, NotifyOnSourceUpdated=True}" SelectedValuePath="Key" ItemsSource="{Binding MyModes}" DisplayMemberPath="Value" > 
       <i:Interaction.Triggers> 
        <i:EventTrigger EventName="SourceUpdated"> 
          <i:InvokeCommandAction Command="{Binding DataContext.SetModeCommand,RelativeSource={RelativeSource AncestorType=UserControl,Mode=FindAncestor}}" CommandParameter="{Binding}" ></i:InvokeCommandAction> 
        </i:EventTrigger> 
       </i:Interaction.Triggers> 
      </ComboBox> 
+0

好。這是一個很好的解決方案! –