为什么此 xamarin 绑定转换器使应用程序崩溃?



我有一个布尔属性,我想将其否定值(!value(绑定到一个按钮,但每次我在 xaml 标签中配置转换器时,它都会无一例外地终止应用程序,我没有在应用程序中心发现任何错误。如果我删除这部分, Converter={StaticResource inverter}}一切将再次运行,但没有转换。

我的 xaml:

<ContentPage.Resources>
<local:BooleanConverter x:Key="inverter" />
...
<ContentPage.Resources>
...
<controls:FrameButton IsEnabled="{Binding IsBusy, Converter={StaticResource inverter}}" Margin="5" CornerRadius="5">

还有我的布尔转换器.cs:

using System;
using Xamarin.Forms;
public class BooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return !System.Convert.ToBoolean(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return !System.Convert.ToBoolean(value);
}
}

更新 1

框架按钮代码:

using Xamarin.Forms;
namespace CustomControls.Controls
{
public class FrameButton : Frame
{
public FrameButton()
{
var MyTapGesture = new TapGestureRecognizer();
MyTapGesture.Tapped += (sender, e) => { Clicked(); };
GestureRecognizers.Add(MyTapGesture);
}
public async void Clicked()
{
await this.ScaleTo(1.1, 100);
await this.ScaleTo(1, 100);
}
}
}

使用显式强制转换,因为您始终知道value将是布尔值,除非您使用错误。通常不使用ConvertBack,因为它通常没有意义。

using System;
using Xamarin.Forms;
public class BooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return !((bool)value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

也许是因为它试图将 IsEnabled 值转换回来。 您是否尝试过将其制作OneWay

例如
IsEnabled="{Binding IsBusy, Mode=OneWay, Converter={x:StaticResource BooleanConverter}}"

根据您的评论进行编辑。

我认为SEGSEGV错误是内存分段错误,即内存读取错误。所以也许inverter没有找到。

我发现其中一些深奥的错误消息通常是由 XAML 代码中的错误触发的。

我看到您的页面转换器声明是:

<ContentPage.Resources>
<local:BooleanConverter x:Key="inverter" />
...
<ContentPage.Resources>

通常声明是:

<ContentPage.Resources>
<ResourceDictionary>
<local:BooleanConverter x:Key="inverter" />
...
</ResourceDictionary>
<ContentPage.Resources>

我怀疑与被调用的密钥"逆变器"的关系没有声明,因为它不在ResourceDictionary

最新更新