我考虑过的另一种方法是创建 AttachedProperties
ListViewItem 上的颜色。唯一的问题是我不确定我会如何
与他们绑定。
你是对的使用附加属性这就是可以做到的。
Step 1。定义您的附加属性
public static Brush GetPointerOverBackground(DependencyObject obj)
{
return (Brush)obj.GetValue(PointerOverBackgroundProperty);
}
public static void SetPointerOverBackground(DependencyObject obj, Brush value)
{
obj.SetValue(PointerOverBackgroundProperty, value);
}
public static readonly DependencyProperty PointerOverBackgroundProperty =
DependencyProperty.RegisterAttached("PointerOverBackground", typeof(Brush), typeof(YourStaticClass), new PropertyMetadata(null));
Step 2。为附加属性定义默认值
<Setter Property="local:YourStaticClass.PointerOverBackground" Value="LightBlue" />
Step 3。在您的视觉状态中使用附加属性
<VisualState x:Name="PointerOver">
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{TemplateBinding local:YourStaticClass.PointerOverBackground}" />
</ObjectAnimationUsingKeyFrames>
</VisualState>
Step 4。创建一个定义所有画笔的接口
这样做的原因是我们可以稍后转换该对象(即BasicItem
) 绑定到每个模板界面,无需知道其具体类型。当然你的BasicItem
应该实施这个界面.
public interface ISupportListViewItemBrushes
{
SolidColorBrush PointerOverBrush { get; set; }
Step 5。创建一个Behavior
负责分配Brush
es to ListViewItem
s
这就是一切都聚集在一起的地方。首先我们需要安装XAML 行为 Nuget 包 https://www.nuget.org/packages/Microsoft.Xaml.Behaviors.Uwp.Managed/。之后,创建一个Behavior
called SupportListViewItemBrushesBehavior
并使其只能连接到ListView
.
public class SupportListViewItemBrushesBehavior : Behavior<ListView>
ListView
有一个名为ContainerContentChanging
我们可以访问每个ListViewItem
及其底层Item
(i.e. BasicItem
/ISupportListViewItemBrushes
) 目的。最后,我们只需使用SetAttachedPropertyName
方法来分配相应的Brush
to the ListViewItem
像下面这样
private void OnContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
{
if (!args.InRecycleQueue &&
args.ItemContainer is ListViewItem container &&
args.Item is ISupportListViewItemBrushes brushes)
{
Helper.SetPointerOverBackground(container, brushes.PointerOverBrush);
}
}
就这样!
请注意,我们必须创建Behavior
这里因为UWP不支持FindAncestor
尚未绑定。或者,不使用附加属性 and a Behavior
,你可以扩展ListView
/ListViewItem
达到同样的结果。
我已经包含了一个小样本here https://github.com/JustinXinLiu/DynamicListViewItemColorsRepo供你参考。这是最终结果。希望这可以帮助!