C#学习教程:样式设置器中的行为不起作用"using:Microsoft.Xaml.Interactivity"xmlns:core="using:Microsoft.Xaml.Interactions.Core"这是风格:这是我的行为:[DefaultEvent(typeof(ScrollViewer),"DoubleTapped")]publicclassScrollViewerDoubleTap:DependencyObject,IAction{publicobjectExecute(objectsender,objectparameter){ScrollViewersv=(ScrollViewer)sender;如果(sv.Horizo??ntalScrollBarVisibility==ScrollBarVisibility.Disabled){sv.Horizo??ntalScrollBarVisibility=ScrollBarVisibility.Hidden;}else{sv.Horizo??ntalScrollBarVisibility=ScrollBarVisibility.Disabled;}返回发件人;这就是我使用它的方式:当我双击具有这种风格的页面上的第一张图片时,效果很好;但是,当我双击页面上的其他图像时,行为代码永远不会运行。我知道它永远不会运行,因为我用断点运行它,当我双击第一张图片而不是第二张图片时它会中断。我很感激为什么会这样。这是行不通的,因为行为、动作或触发器被设计为附加到单个元素。当您在样式的设置器中定义它时,就像您试图将它与多个元素相关联一样,如您所见,只有当您使用此样式触发器与第一个元素交互时才会调用它。有一种简单的方法可以解决这个问题。基本上,您需要确保与此样式关联的每个元素都有您创建的触发器的新实例。您可以将所有这些逻辑包装在一个附加属性中,然后您的样式只需要引用这个属性。这就是附加属性的实现方式。publicstaticclassFrameworkElementEx{publicstaticboolGetAttachBehaviors(DependencyObjectobj){return(bool)obj.GetValue(AttachBehaviorsProperty);}publicstaticvoidSetAttachBehaviors(DependencyObjectobj,boolvalue){obj.SetValue(staty)行为只读;privatestaticvoidCallback(DependencyObjectd,DependencyPropertyChangedEventArgse){varbehaviors=Interaction.GetBehaviors(d);vareventTriggerBehavior=newEventTriggerBehavior{EventName="DoubleTapped"};eventTriggerBehavior.Actions.Add(newScrollViewerDoubleTap());行为。添加(事件触发行为);我们可以使用纯XAML和Reusable附加属性来执行此操作,该属性接收带有BehaviorCollection(或单个Behavior)的DataTemplate。您不需要更改代码隐藏。或者,如果您一次只需要一些Behaviors:Dependencies,您甚至不需要更改它。使用Microsoft.Xaml.Interactivity;使用Windows.UI.Xaml;使用系统;命名空间MyBehaviors{publicstaticclassAttachedBehaviorsEx{publicstaticDataTemplateGetAttachedBehaviors(DependencyObjectobj){return(DataTemplate)obj.GetValue(AttachedBehaviorsProperty);}publicstaticvoidSetAttachedBehaviors(DependencyObjectobj,DataTemplatevalue){obj.SetValue(AttachedBehaviorsProperty,value);}publicstaticreadonlyDependencyPropertyAttachedBehaviorsProperty=DependencyProperty.RegisterAttached("AttachedBehaviors",typeof(DataTemplate),typeof(AttachedBehaviorsEx),newPropertyMetadata(null,Callback));privatestaticvoidCallback(DependencyObjectd,DependencyPropertyChangedEventArgse){BehaviorCollectioncollection=null;vartemplate=(DataTemplate)e.NewValue;if(template!=null){varvalue=template.LoadContent();如果(值为BehaviorCollection)集合=(BehaviorCollection)值;elseif(值为IBehavior)cocollection=newBehaviorCollection{value};elsethrownewException($"AttachedBehaviors应该是BehaviorCollection或IBehavior。");}//如果e.NewValue为空,则此处的集合可能为空Interaction.SetBehaviors(d,collection);}}}为什么更好?这是一种比JustinXL建议的更灵活的方法。他的代码需要修改代码隐藏才能重用它。每次要重用它时,都需要设置EventName(在这一行中EventName="DoubleTapped")和Behavior(在这一行中eventTriggerBehavior.Actions.Add(newScrollViewerDoubleTap());)。以上就是C#学习教程的全部内容:BehaviorinStyleSetterdoesnotworkingproperly。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。涉及侵权,请点击维权联系管理员删除。如需转载请注明出处:
