Xamarin Binding 功能作为具有数据绑定的列表视图中的 ImageSource



我正在尝试在下面的列表视图中可视化一个名为MinRepresentation的对象的状态。

我想绑定函数ImageSource stateImage(MinRepresentationState state),在那里我交接状态并取回图像源。

我的问题是,通过 xaml 访问函数并传递参数。

Visible OrdersMinRepresentation的集合,每个都包含State

<ListView HasUnevenRows="True" SelectionMode="Single" ItemsSource="{Binding VisibleOrders}" ItemSelected="OnListViewItemSelected" ItemTapped="OnListViewItemTapped">
***OTHER STUFF***
<StackLayout Orientation="Horizontal" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3" Padding= "0,5,0,5" BackgroundColor="#CC3F6E3F">
<Image Source="{Binding stateImage(State)" Margin="10,0,0,0" />
<Label Text="{Binding Id, StringFormat='ID: [{0}]'}" FontSize="Small" Margin="5,0,0,0" FontAttributes="Bold" TextColor="#FFFFFF"/>
</StackLayout>
***OTHER STUFF***
</ListView>
public ImageSource stateImage(MinRepresentationState state)
        {
            switch (state)
            {
                case MinRepresentationState.Assigned:
                    return ImageSource.FromResource("state_assigned.png");
            }
        }

您可以使用 IValueConverter 来实现这一点。创建一个IValueConverter类并将逻辑代码放在其中:

public class StateToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        MinRepresentationState representationState = (MinRepresentationState)value;
        if (representationState == MinRepresentationState.Assigned)
        {
            return "state_assigned.png";
        }
        return "otherImage.png";
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在 XAML 中使用它,如下所示:

<!--Define it in resources-->
<ContentPage.Resources>
    <local:StateToImageConverter x:Key="StateToImageConverter"/>
</ContentPage.Resources>
<!--Use converter-->
<Image Source="{Binding State, Converter={StaticResource StateToImageConverter}}" Margin="10,0,0,0"/>

只能绑定到公共属性。 在模型上创建状态图像属性

public string StateImage 
{
  get {
    switch (State)
    {
      case MinRepresentationState.Assigned:
        return "state_assigned.png";
    }
  }
}

还可以使用DataTrigger在 XAML 中设置图像

<Image Source="state_default.png" Margin="10,0,0,0">
    <Image.Triggers>
        <DataTrigger TargetType="Image" Binding="{Binding State}" Value="Assigned">
            <Setter Property="Source" Value="state_assigned.png" />
        </DataTrigger>
    </Image.Triggers>
</Image>

参考: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#data

最新更新