【发布时间】:2018-06-10 22:17:00
【问题描述】:
我正在使用 c# 和 wpf。
我遇到了数据绑定问题。 我有这个模型基类:
public class Media
{
public string Text {get;set;}
public List<string> Videos{get;set;}
public List<string> Images{get;set;}
}
这是我的 xaml 代码:
<Grid Height="500" Width="380">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Text, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" TextAlignment="Center" VerticalAlignment="Center"/>
<Image Grid.Row="1" Source="{Binding Images[0], Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Visibility="{Binding Converter={StaticResource imageVisibilityConverter}}"/>
<MediaElement Grid.Row="1" Source="{Binding Videos[0], Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Visibility="{Binding Converter={StaticResource videoVisibilityConverter}}"/>
</Grid>
在我的媒体列表视图模型中,我的一些模型没有任何视频并且视频为空(或没有任何项目)。 在 MediaElement 的绑定源中,我输入了导致异常的视频的 [0] 值。
例外:
System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type 'XXXX') from 'Videos' (type 'List`1'). BindingExpression:Path=Videos[0]; DataItem='Media' (HashCode=18855696); target element is 'MediaElement' (Name=''); target property is 'Source' (type 'Uri') ArgumentOutOfRangeException:'System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: index'
我想检查视频是否可用,如果没有,请将 Videos[0] 设置为 MediaElement 源属性,不要对此属性进行任何设置。
任何帮助将不胜感激。
【问题讨论】:
-
您是否考虑过确保集合始终存在?这样,列表中有 no 项的模式与有 有 项时的模式相同。
-
我不能,因为我必须从服务器端获取这个集合。即使我可以这样做,仍然有这个问题,因为我没有该特定帖子的任何视频链接!
-
仅仅因为数据来自服务器端并不意味着你不能。除非您说 服务器端 是您无法更改的第三方组件。听起来您正在使用从服务器返回的对象作为 ViewModel(不仅仅是模型),这让“尾巴摇摆不定”。如果 ViewModel 由您定义,您可以定义“FirstVideo”属性以返回集合中的第一个,如果集合为 null,则返回 null;那么您可以绑定到该属性,而不需要 XAML 中的硬编码索引器和转换器。
标签: c# wpf data-binding