我有一个 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 中绑定方法,您可以使用以下两种方法之一:
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}}" />
public class SearchResultDto
{
public bool IsOne { get; set; }
public bool IsTwo { get; set; }
public bool IsBoth => IsOne && IsTwo;
}
<VerticalStackLayout IsVisible="{Binding IsBoth}" />