问题描述
遇到这样的问题,如果你把ImageButton
和visualstatemanager
一起使用并点击它,然后将手指滑出控件并松开,那么状态不会重置为normal。
有人知道如何解决这个问题吗?
以下是 ImageButton 样式的示例:
<Style x:Key="ProductButton" targettype="ImageButton">
<Setter Property="HeightRequest" Value="70"/>
<Setter Property="WidthRequest" Value="210"/>
<Setter Property="Aspect" Value="Fill"/>
<Setter Property="CornerRadius" Value="4"/>
<Setter Property="visualstatemanager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="normal">
<VisualState.Setters>
<Setter Property="Opacity" Value="1"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="pressed">
<VisualState.Setters>
<Setter Property="Opacity" Value="0.8"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
解决方法
我找到了一种解决方法,它使用平台效应,当在 Imagebutton 之外发生触摸时触发释放的事件。
在.NET Standard 库中创建效果(共享代码)。
public class SpecialButtonEffect : RoutingEffect
{
public SpecialButtonEffect() : base($"MyCompany.{nameof(SpecialButtonEffect)}")
{
}
}
在 ios 中实现 SpecialButtonEffect:
[assembly: ResolutionGroupName("MyCompany")]
[assembly: ExportEffect(typeof(EffectTest.iOS.Effects.SpecialButtonEffect),nameof(EffectTest.iOS.Effects.SpecialButtonEffect))]
namespace EffectTest.iOS.Effects
{
public class SpecialButtonEffect : PlatformEffect
{
protected override void OnAttached()
{
(Control as UIButton).TouchUpOutside += OnTouchUpOutside;
}
protected override void OnDetached()
{
(Control as UIButton).TouchUpOutside -= OnTouchUpOutside;
}
private void OnTouchUpOutside(object sender,EventArgs e)
{
(Element as IButtonController).SendReleased();
}
}
}
在 xaml 中使用效果。
<ImageButton
HorizontalOptions="Center"
Source="favorite.png"
VerticalOptions="CenterAndExpand">
<ImageButton.Effects>
<local:SpecialButtonEffect />
</ImageButton.Effects>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal">
<VisualState.Setters>
<Setter Property="Scale" Value="1" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Pressed">
<VisualState.Setters>
<Setter Property="Scale" Value="0.5" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</ImageButton>