.Net Maui 7样式中的调用目标引发了异常

9vw9lbht  于 2023-03-20  发布在  .NET
关注(0)|答案(2)|浏览(145)

我有一个自己开发的控件,它有一个属性,如下:

public TextAlignment HorizontalIconAlignment { get { return (TextAlignment)GetValue(HorizontalIconAlignmentProperty); } set { SetValue(HorizontalIconAlignmentProperty, value); } }
public static readonly BindableProperty HorizontalIconAlignmentProperty = BindableProperty.Create("HorizontalTextAlignment", typeof(TextAlignment), typeof(DuoToneIcon), TextAlignment.Start, propertyChanged: OnHorizontalIconAlignmentPropertyChanged);
private static void OnHorizontalIconAlignmentPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    var control = (myControl)bindable;
    control.Label.HorizontalTextAlignment = (TextAlignment)newValue;
}

我可以非常正常地使用它如下:

<local:myControl Text="Something" HorizontalIconAlignment="Center" PrimaryColor="red" />

问题是,我不想在整个软件中重复这个属性,因此我在我的Style.xaml中添加了它作为样式,如下所示:

<Style TargetType="local:myControl">
    <Setter Property="PrimaryColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource Gray900}}" />
</Style>

它的工作完美,但当我改变它如下图,并添加HorizontalIconAlignment,然后我收到一个异常。

<Style TargetType="local:myControl">
    <Setter Property="PrimaryColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource Gray900}}" />
    <Setter Property="HorizontalIconAlignment" Value="Center" />
</Style>

我做错什么了吗?
接收:
Microsoft.Maui.Controls.Xaml.XamlParseException:'位置10:37。类型转换器失败:调用的目标引发了异常。“
XmlInfo:资源/样式/样式.xaml

iugsix8n

iugsix8n1#

在您的代码中:

public static readonly BindableProperty HorizontalIconAlignmentProperty = 
      BindableProperty.Create("HorizontalTextAlignment", typeof(TextAlignment), typeof(DuoToneIcon), TextAlignment.Start, propertyChanged: OnHorizontalIconAlignmentPropertyChanged);

它应该是BindableProperty.Create("HorizontalIconAlignment",而不是HorizontalTextAlignment。BindableProperty.Create中的属性名称应该与您所删除的属性名称相同。
另外,第二个类型应该是控件,所以应该是:

public static readonly BindableProperty HorizontalIconAlignmentProperty = 
      BindableProperty.Create("HorizontalIconAlignment", typeof(TextAlignment), 
           typeof(myControl), TextAlignment.Start, propertyChanged: OnHorizontalIconAlignmentPropertyChanged);

有关详细信息,请参阅有关创建可绑定属性的官方文档

wgeznvg7

wgeznvg72#

<Style TargetType="local:myControl">
        <Setter Property="PrimaryColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource Gray900}}" />
        <Setter Property="HorizontalIconAlignment" Value="{AppThemeBinding Center}" />
    </Style>

我认为绑定丢失,您可以尝试添加此绑定作为示例。

相关问题