我是一個業餘愛好者的程序員誰卡住了的東西應該是比較簡單的刷新時,不觸發組合框的SelectionChanged ......但我不見天日:從後端
情況:一個簡單的XAML/MVVM/VB.Net應用程序,它爲用戶提供了一個可以調入的廣播電臺的Combobox。當選擇一個電臺,應用程序發送的命令調整對進一步處理和實際調整服務器(與LogitechMediaServer/Squeezebox的人們將能夠拍下這相當不錯:)
但:此外,還存在被調諧的電臺通過除此應用以外的其他方式改變的可能性。出於這個原因,存在「刷新」按鈕以獲得當前調諧到廣播電臺。
示例代碼是高度有限的用戶控件的一部分。正因爲如此,我希望ComboBox既可以用作選擇器,也可以用來提供當前狀態(無線電臺調入的方式)。
問題:當從服務器刷新狀態時,SelectionChanged事件再次觸發,這會向服務器發送另一個Tune請求。我不希望發生這種情況。我們如何才能確保SelectRadioStation()RelayCommand僅在用戶選擇不同的廣播電臺時觸發,而不是在從服務器更新電臺時觸發?
注意:可能但不是首選解決方案:添加一個額外的文本塊,顯示調整到的實際電臺,並將其綁定到SelectedRadioStation。由於用戶控件的高度,我並不是很想要這樣,而且更喜歡只有1個組合框。
的MVVM模式是這樣的:
Public Class ViewModel
Inherits ViewModelBase
Public Property RadioStations As List(Of String)
Public Property SelectedRadioStation As String
Get
Return _SelectedRadioStation
End Get
Set(value As String)
_SelectedRadioStation = value
RaisePropertyChanged()
End Set
End Property
Private Property _SelectedRadioStation As String
Public ReadOnly Property SelectRadioStation As RelayCommand(Of Object)
Get
Return New RelayCommand(Of Object)(Sub(x)
Await SendSelectedRadioStationToServer()
Debug.WriteLine(String.Format("ViewModel.SelectRadioStation - executed : {0}", x.ToString))
End Sub)
End Get
End Property
Public ReadOnly Property SetRadioStation As RelayCommand
Get
Return New RelayCommand(Sub()
SelectedRadioStation = "Radio 1"
End Sub)
End Get
End Property
Public Sub New()
RadioStations = New List(Of String)
End Sub
End Class
,並簡化應用程序是這樣的:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ComboBox Grid.Row="0" x:Name="RadioStationList" ItemsSource="{Binding RadioStations}" SelectedItem="{Binding SelectedRadioStation, Mode=TwoWay}">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="SelectionChanged" >
<Core:InvokeCommandAction Command="{Binding SelectRadioStation}" CommandParameter="{Binding SelectedItem, ElementName=RadioStationList}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</ComboBox>
<Button Grid.Row="1" Content="Refresh Radio by Querying the server to see to which station the radio actually is tuned to" Command="{Binding SetRadioStation}"/>
</Grid>
而且的MainPage的OnNavigatedTo(只是用於測試)
Protected Overrides Async Sub OnNavigatedTo(e As NavigationEventArgs)
myVM.RadioStations.Add("Radio 1")
myVM.RadioStations.Add("Radio 2")
myVM.RadioStations.Add("Radio 3")
myVM.RadioStations.Add("Radio 4")
myVM.SelectedRadioStation = "Radio 3"
DataContext = myVM
End Sub