例如,使用ViewModel中的命令单击图像时,最简单的方法是例如将图像旋转180度?我正在使用棱镜。
由于点击后还包含一些逻辑,所以我尝试将其与Gesture Regognizer和事件处理程序混合使用,但是不能很好地协同工作。
答案 0 :(得分:0)
您可能会发现Dave Britch的行为库对此很有用。在他的博客中对此进行了描述:
https://www.davidbritch.com/2016/07/xamarinforms-behaviors-rotateaction.html
他的博客的片段:
下面的代码示例演示如何使用EventHandlerBehavior和RotateAction类实现一种复合动画,该动画同时在X,Y和Z轴上旋转Image控件:
<Image x:Name="image" Source="monkey.png" Opacity="0" VerticalOptions="CenterAndExpand" />
<Button Text="Run Animation">
<Button.Behaviors>
<behaviors:EventHandlerBehavior EventName="Clicked">
<!-- Compound Animation -->
<behaviors:RotateAction TargetObject="{x:Reference image}"
Duration="600000"
FinalAngle="110520" />
<behaviors:RotateAction TargetObject="{x:Reference image}"
Duration="600000"
FinalAngle="90360"
Axis="X" />
<behaviors:RotateAction TargetObject="{x:Reference image}"
Duration="600000"
FinalAngle="71640"
Axis="Y" />
</behaviors:EventHandlerBehavior>
</Button.Behaviors>
</Button>
答案 1 :(得分:0)
您可以在视图模型中定义一个新属性,以指示是否应该旋转图像:
private bool _showImageRotated;
public bool ShowImageRotated
{
get => _showImageRotated;
set => SetProperty(ref _showImageRotated, value);
}
然后,在XAML代码中,您可以使用从布尔值到双精度的转换器– Rotation
属性expects the degrees of the rotation as a double将此属性绑定到Image
元素的属性Rotation
为此,请定义一个新的转换器:
public class BooleanToDegreesConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? 180 : 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
将此新转换器注册到您的App.xaml
文件中:
<converters:BooleanToDegreesConverter x:Key="BooleanToDegrees" />
然后使用它将图像的Rotation
属性绑定到您在viewmodel中定义的新布尔属性:
<Image
...
Rotation="{Binding ShowImageRotated, Converter={StaticResource BooleanToDegrees}}"
... />
执行此操作后,根据属性ShowImageRotated
的值,图像将显示为旋转或正常状态。
您可以使用动画来旋转图像,而不是创建和使用转换器,只需将其添加到视图背后的代码中即可。
private YourViewModel _viewModel;
...
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
if (_viewModel != null)
{
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
_viewModel = BindingContext as YourViewModel;
if (_viewModel != null)
{
// Subscribe to the viewmodel property changes to know when to start
// the rotation
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
// Set the intial rotation angle
YourImage.Rotation = _viewModel.ShowImageRotated ? 180 : 0;
}
}
private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(YourViewModel.ShowImageRotated):
// If the property ShowImageRotated changes, start the animation
RotateImageWithAnimation();
break;
}
}
private void RotateImageWithAnimation()
{
if (_viewModel != null)
{
var startAngle = _viewModel.ShowImageRotated ? 0 : 180;
var endAngle = _viewModel.ShowImageRotated ? 180 : 0;
new Animation(v => YourImage.Rotation = v, startAngle, endAngle).Commit(this, "Image rotation");
}
}
我希望这会有所帮助!