起初我尝试使用VisualStateManger,但后来我决定换一种方式。我创建了一个存储它的依赖属性会突出显示颜色,它可以像这样使用:
<ListBoxItem Name="Missed" local:DependencyPhoneClass.ColorOfState="{StaticResource MissedForegroundColor}">
依赖属性类代码:
public class DependencyPhoneClass : DependencyObject
{
public static DependencyProperty ColorOfStateProperty;
public static void SetColorOfState(DependencyObject DepObject, Brush value)
{
DepObject.SetValue(ColorOfStateProperty, value);
}
public static Brush GetColorOfState(DependencyObject DepObject)
{
return (Brush)DepObject.GetValue(ColorOfStateProperty);
}
static DependencyPhoneClass()
{
ColorOfStateProperty = DependencyProperty.RegisterAttached("CollorOfState",
typeof(Brush),
typeof(DependencyPhoneClass),
new PropertyMetadata(OnColorStateNameChanged));
}
private static void OnColorStateNameChanged(object sender, DependencyPropertyChangedEventArgs args)
{
var MyListBoxItem = sender as ListBoxItem;
if (MyListBoxItem == null)
{
throw new InvalidOperationException("This attached property only supports types derived from Control");
}
Brush ColorOfState = GetColorOfState(MyListBoxItem);
if (ColorOfState != null)
{
MyListBoxItem.Foreground = ColorOfState;
}
}
}
我在资源中创建了颜色:
<Window.Resources>
<SolidColorBrush x:Key="DefaultForegroundColor" Color="Black" />
<SolidColorBrush x:Key="MissedForegroundColor" Color="Red" />
<SolidColorBrush x:Key="UnansweredForegroundColor" Color="OrangeRed" />
</Window.Resources>
列表框:
<ListBox Name="PhoneListBox" HorizontalAlignment="Center" VerticalAlignment="Top" Width="370" Height="100">
<ListBoxItem Name="Missed" local:DependencyPhoneClass.ColorOfState="{StaticResource MissedForegroundColor}" Content="Daddy: 1" />
<ListBoxItem Name="Unanswered" local:DependencyPhoneClass.ColorOfState="{StaticResource UnansweredForegroundColor}" Content="Mom: 15" />
<ListBoxItem Name="Normal" local:DependencyPhoneClass.ColorOfState="{StaticResource DefaultForegroundColor}" Content="Kim: 0" />
</ListBox>
现在,颜色已设置,选择时必须将其重置为默认值。这可以通过多种方式完成:
使用代码:
private void ListBoxItem_Selected(object sender, RoutedEventArgs e)
{
ListBoxItem MyListBoxItem = sender as ListBoxItem;
Brush DefaultColor = this.Resources["DefaultForegroundColor"] as Brush;
DependencyPhoneClass.SetColorOfState(MyListBoxItem, DefaultColor);
}
或者在 XAML 中使用 EventTrigger:
<ListBoxItem.Triggers>
<EventTrigger RoutedEvent="ListBoxItem.Selected">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Missed" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource DefaultForegroundColor}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ListBoxItem.Triggers>