【发布时间】:2014-02-22 20:48:40
【问题描述】:
我正在尝试使用 DataTemplate 在列表视图单元格中显示文本 + 图像。
<ListView
HorizontalAlignment="Stretch"
VerticalContentAlignment="Stretch"
HorizontalContentAlignment="Center"
Name="PlaybackListView"
VerticalAlignment="Top"
ItemsSource="{Binding Playbacks}"
IsSynchronizedWithCurrentItem="True">
<ListView.Resources>
<DataTemplate x:Key="StatusCellTemplate">
<WrapPanel>
<TextBlock Name="StatusTextBlock" Width="Auto" Text="{Binding Status}" />
<Image Source="{Binding Converter={StaticResource PlaybackViewItemToStatusImageSource}}" Height="14" Width="14" />
</WrapPanel>
</DataTemplate>
</ListView.Resources>
<ListView.View>
<GridView>
<! -- Columns -->
<GridViewColumn
Header="Status"
Width="130"
CellTemplate="{StaticResource StatusCellTemplate}" />
<! -- Columns -->
</GridView>
</ListView.View>
问题是有时会显示图标,但有时却不显示。即使使用相同的源路径。
这是我在绑定中使用的 ValueConverter 的转换方法:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
object result = value;
PlaybackViewItem item = value as PlaybackViewItem;
if (item != null)
{
switch (item.Status)
{
case PlaybackStatus.FilePreparationFinished:
case PlaybackStatus.RadioPreparationFinished:
case PlaybackStatus.Started:
result = Path.Combine(IconsPath, "SignCheck.png");
break;
case PlaybackStatus.Finished:
// HasPlaybackErrors is always false
result = Path.Combine(IconsPath, !item.HasPlaybackErrors ? "SignCheck.png" : "WarningYellow.png");
break;
case PlaybackStatus.RadioPreparationFailed:
case PlaybackStatus.FilePreparatinoFailed:
case PlaybackStatus.CannotBeStarted:
case PlaybackStatus.Failed:
case PlaybackStatus.Stopped:
result = Path.Combine(IconsPath, "SignExclamation.png");
break;
default:
result = null;
break;
}
}
else
{
result = null;
}
return result;
}
在上图中,您可以看到在一种情况下,即使它具有相同的状态,它也不会显示图像。
调试输出中也没有绑定错误或任何内容。
【问题讨论】:
-
路径不必相同。如果
HasPlaybackErrors == true则将使用 WarningYellow.png。你有这个文件吗? -
是的,所有文件都存在并且 HasPlaybackErrors 被硬编码为 false
-
Finished是它的初始值吗?当Status发生变化时,您的图标不会自动刷新。您可以通过Snoop 检查Image上Source的当前值是多少 -
好的,我发现了问题,它在图像的绑定中。我直接绑定到我使用的 ViewItem,当它添加到列表中时,这只会“更改”一次。因此,我的值转换器仅在初始状态下调用。我需要绑定到我的视图项的“状态”属性,但仍然在我的转换器中获取整个 ViewItem,以便我可以检查“HasPlaybackErrors”属性。
-
使用
IMultiValueConverter而不是IValueConverter和MultiBinding