我有一個定義自定義ControlTemplate的ListBox。所選項目具有改變背景和前景的樣式,並且樣式基本上起作用。但是,我想介紹一種行爲,在選擇更改時顯示模態消息框,詢問用戶是否真的想要選擇不同的項目。我已經實現了一個ICommand來做到這一點,下面的代碼顯示爲AreYouSureCommand。XAML樣式將不會應用,直到EventTrigger命令完成
問題出現在顯示模式消息框時,所選項目的背景樣式發生變化,但前景不變。只要我關閉模式消息框,前景色就會改變。我沒有包含ICommand的代碼,因爲它有點複雜,但希望在執行時用ShowDialog打開一個窗口就足夠了。
任何人都可以解釋爲什麼我的背景顏色改變,但不是我的前景色嗎?
<ListBox x:Name="SubMenu" ItemsSource="{Binding MyItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=DisplayName}"
Foreground="{Binding Foreground, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="MainBorder">
<ContentControl x:Name="Presenter">
<ContentPresenter />
</ContentControl>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<!-- Setter on MainBorder applies before AreYouSureCommand completes -->
<Setter TargetName="MainBorder" Property="Background" Value="Red" />
<!-- Setter on Presenter applies after AreYouSureCommand completes -->
<Setter TargetName="Presenter" Property="Foreground" Value="Green" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding AreYouSureCommand}"
CommandParameter="{Binding SelectedItem, ElementName=SubMenu}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
如果更改XAML中的順序發生相反的情況? –
有趣的想法,但沒有 - 如果我扭轉順序,同樣的事情發生 - 背景顏色改變,但前景不會改變,直到我解散模態消息框。 – wwarby
我想你會將前景設置爲數據模板中的特定值,並且觸發器無法更改它。嘗試刪除'Foreground'屬性並將其作爲默認樣式添加到ListBoxItem的樣式標記中? – Ben