行为无法在样式设置器中正常工作
作者:互联网
在我的Windows运行时应用程序中,我有一个主题,其样式具有为DoubleTapped动作定义的“行为”:
这些是XML命名空间:
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
这是样式:
<Style x:Name="DisplayImage" TargetType="ScrollViewer">
<Setter Property="VerticalScrollBarVisibility" Value="Hidden" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="ZoomMode" Value="Disabled" />
<Setter Property="i:Interaction.Behaviors">
<Setter.Value>
<i:BehaviorCollection>
<core:EventTriggerBehavior EventName="DoubleTapped">
<local:ScrollViewerDoubleTap />
</core:EventTriggerBehavior>
</i:BehaviorCollection>
</Setter.Value>
</Setter>
</Style>
这是我的行为:
[DefaultEvent(typeof(ScrollViewer),"DoubleTapped")]
public class ScrollViewerDoubleTap : DependencyObject, IAction
{
public object Execute(object sender, object parameter)
{
ScrollViewer sv = (ScrollViewer)sender;
if (sv.HorizontalScrollBarVisibility == ScrollBarVisibility.Disabled)
{
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
}
else
{
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
return sender;
}
}
这就是我的使用方式:
<ScrollViewer Style="{StaticResource Image}" MaxWidth="1067">
<Border BorderBrush="Black" BorderThickness="1">
<Image Source="MyImage.png"/>
</Border>
</ScrollViewer>
当我双击具有这种样式的页面上的第一张图像时,它可以完美工作;但是,当我双击页面上的其他图像时,行为代码将永远不会运行.我知道它永远不会运行,因为我使用断点来运行它,并且当我双击第一个图像而不是第二个图像时,它会中断.我将感谢所有提示,说明为什么会发生这种情况.
解决方法:
这行不通,因为行为,动作或触发器被设计为附加到单个元素.当您在样式的设置器中定义它时,就像您正在尝试将其与多个元素相关联,并且正如您已经看到的那样,仅当您与具有该样式的第一个元素进行交互时才调用触发器.
有一种简单的方法可以解决此问题.基本上,您需要确保与此样式相关联的每个元素都具有您创建的触发器的新实例.您可以将所有这些逻辑包装在附加属性中,然后您的样式只需引用该属性.
<Style x:Name="DisplayImage" TargetType="ScrollViewer">
<Setter Property="VerticalScrollBarVisibility" Value="Hidden" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="ZoomMode" Value="Disabled" />
<Setter Property="local:FrameworkElementEx.AttachBehaviors" Value="True" />
</Style>
这是实现此附加属性的方式.
public static class FrameworkElementEx
{
public static bool GetAttachBehaviors(DependencyObject obj)
{
return (bool)obj.GetValue(AttachBehaviorsProperty);
}
public static void SetAttachBehaviors(DependencyObject obj, bool value)
{
obj.SetValue(AttachBehaviorsProperty, value);
}
public static readonly DependencyProperty AttachBehaviorsProperty =
DependencyProperty.RegisterAttached("AttachBehaviors", typeof(bool), typeof(FrameworkElementEx), new PropertyMetadata(false, Callback));
private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behaviors = Interaction.GetBehaviors(d);
var eventTriggerBehavior = new EventTriggerBehavior
{
EventName = "DoubleTapped"
};
eventTriggerBehavior.Actions.Add(new ScrollViewerDoubleTap());
behaviors.Add(eventTriggerBehavior);
}
}
标签:winrt-xaml,windows-runtime,c 来源: https://codeday.me/bug/20191028/1955287.html