【发布时间】:2020-06-27 10:49:11
【问题描述】:
我有问题。我想要做的是从 ViewModel 绑定一个 ImageSource。图像文件名为 ledstrip.png,位于 Resources/Drawable 文件夹中。我正在使用以下 xaml:
<ListView ItemsSource="{Binding knownDeviceList}" SelectionMode="None" RowHeight="90">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<AbsoluteLayout HeightRequest="70" Margin="20,20,20,0">
<StackLayout Opacity="0.3" BackgroundColor="White"
AbsoluteLayout.LayoutBounds="0,0,1,1"
AbsoluteLayout.LayoutFlags="All" />
<StackLayout AbsoluteLayout.LayoutBounds="0,0,1,1"
AbsoluteLayout.LayoutFlags="All">
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="70" />
</Grid.ColumnDefinitions>
<Image Source="{Binding DeviceImage}" Grid.RowSpan="2" Grid.Column="0" Margin="5" />
</Grid>
</StackLayout>
</AbsoluteLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在我的 ViewModel 中,我有以下代码:
public class VM_DeviceList : BindableObject
{
private ObservableCollection<DisplayedDevice> _knownDeviceList;
public ObservableCollection<DisplayedDevice> knownDeviceList
{
get
{
return _knownDeviceList;
}
set
{
if (_knownDeviceList != value)
{
_knownDeviceList = value;
OnPropertyChanged();
}
}
}
public VM_DeviceList()
{
knownDeviceList = new ObservableCollection<DisplayedDevice>();
MyHandler();
}
private async Task LoadKnownDeviceList()
{
foreach (KnownDevice device in App.KnownDeviceList)
{
DisplayedDevice displayedDevice = new DisplayedDevice();
displayedDevice.Id = device.Id;
displayedDevice.Name = device.Name;
switch (device.Type)
{
case "ledstrip":
displayedDevice.DeviceImage = "ledstrip.png";
break;
case "triangle":
displayedDevice.DeviceImage = "triangle.png";
break;
}
knownDeviceList.Add(displayedDevice);
}
}
public Task MyHandler()
{
return LoadKnownDeviceList();
}
public class DisplayedDevice
{
public int Id { get; set; }
public string Name { get; set; }
public string DeviceImage { get; set; }
}
}
问题是当我在 xaml ImageSource 中键入“ledstrip.png”时,图像会显示出来,但是当我像上面显示的方式绑定它时,屏幕上不会出现图像!
我做错了什么,我该如何解决?
【问题讨论】:
-
你试过写
"ledstrip.png"吗? -
是的,但这会导致相同的情况.....没有显示图像
-
在这种情况下什么是“displayedDevice”?
-
不应该是“{Binding NameOfTheClassInstance.DeviceImage}”吗?我不知道您是否在列表中设置绑定
-
另外,尝试只绑定字符串,你不需要创建一个 ImageSource 来在源中绑定,它接受字符串,它会为你获取 Drawable Image
标签: c# xamarin xamarin.forms xamarin.android xamarin.ios