如何在 Maui xaml 中使用方法扩展?

问题描述 投票:0回答:1

我有一个 Dto 对象:

public class SearchResultDto
{
  public bool IsOne { get; set; };

  public bool IsTwo { get; set; }
}

我有一个方法扩展:

public static class SearchResultDtoExtension{
  public static bool IsBoth(this SearchResultDto dto)
  {
    return dto.IsOne && dto.IsTwo;
  }
}

在我的 ViewModel 中,我可以成功使用 searchResultDto.IsBoth();

我希望在 xaml 中使用此扩展,例如:

IsVisible={Binding IsBoth()}

它不起作用。

如何在xaml中使用方法扩展?

我的代码:

<listView:SfListView.ItemTemplate>
    <DataTemplate x:DataType="contracts:SearchResultDto">
            <VerticalStackLayout IsVisible="{Binding **IsBoth()**}"
xaml maui extension-methods
1个回答
0
投票

正如注释中所解释的,您无法在 XAML 中绑定方法,您可以使用以下两种方法之一:

  1. 使用
    ValueConverter
public class IsBothConverter : IValueConverter
{
    public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
        => (value as SearchResultDto)?.IsBoth();


    public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:IsBothConverter x:Key="isBothConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
...

 <VerticalStackLayout IsVisible="{Binding ., Converter={StaticResource isBothConverter}}" />
  1. 使用评论中建议的第三个汽车属性,例如@julian
public class SearchResultDto
{
    public bool IsOne { get; set; }
    public bool IsTwo { get; set; }
    public bool IsBoth => IsOne && IsTwo;
}
 <VerticalStackLayout IsVisible="{Binding IsBoth}" />
© www.soinside.com 2019 - 2024. All rights reserved.