我在我的應用程序中使用硬編碼的WPF NotifyIcon,它使用MVVM Light實現。我正在嘗試爲圖標創建一個自定義TrayPopup。在這個彈出窗口中,我有一個ItemsControl,其ItemsSource是我的ViewModel中的對象「NumberList」的列表。對於我的DataTemplate,我使用了一個顯示我的源對象的「Id」屬性的網格和一個按鈕。我試圖綁定回ViewModel中的RelayCommand按鈕。我在過去通過使用RelativeSource獲取窗口祖先的DataContext的Binding完成了類似的事情。這次我嘗試了類似的方法,但是當我運行該應用程序時,打開TrayPopup,然後單擊按鈕什麼也沒有發生。我的命令沒有在我的ViewModel中被觸發。WPF中的ItemsControl中的按鈕的命令綁定NotifyIcon
作爲一個測試,我嘗試向我的TrayPopup中添加另一個按鈕,並將其命令綁定到ViewModel中的同一個按鈕。該綁定工作正常,所以它不是我所知道的命令。
就像我說過的,我幾乎完全在過去使用這種技術,從來沒有在NotifyIcon中使用過。我已經嘗試在按鈕綁定到我的窗口的名稱中指定ElementName,這沒有奏效。我也嘗試將RelativeSource更改爲父TaskbarIcon,也沒有成功。
以下是對同樣的問題NotifyIcon的一個示例實現:
<tb:TaskbarIcon PopupActivation="LeftOrRightClick">
<tb:TaskbarIcon.TrayPopup>
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="200"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0">
<ItemsControl ItemsSource="{Binding NumberList, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding Id, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Grid.Column="1" Content="Test" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.TestCommand}"/> <!--This binding doesn't work!-->
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
<Button Grid.Row="1" Content="Test2" Command="{Binding TestCommand}"/> <!--This works-->
</Grid>
</tb:TaskbarIcon.TrayPopup>
</tb:TaskbarIcon>
我相當有信心,一切都在視圖模型是正確的,因爲我一直在使用這個應用程序,我寫的先前版本不久以前。到目前爲止,除了這個NotifyIcon之外,我還沒有遇到任何問題。有任何想法嗎?