我有一个用于选择媒体类型的组合框。我希望在选择 .vmw、.mpeg 或 .avi 文件时改变 mediaelement 的高度。如何使用 MVVM 方法实现这一目标?
提前致谢
您可以使用适当的转换器将 MediaElement 的Width
andHeight
直接绑定到其Source
属性,该转换器根据媒体类型选择适当的大小:
<MediaElement
Width="{Binding Path=Source, RelativeSource={RelativeSource Self}, Converter={StaticResource MediaElementSizeConverter}, ConverterParameter=Width}"
Height="{Binding Path=Source, RelativeSource={RelativeSource Self}, Converter={StaticResource MediaElementSizeConverter}, ConverterParameter=Height}"/>
转换器:
public class MediaElementSizeConverter : IValueConverter
{
private const double defaultWidth = 320d;
private const double defaultHeight = 240d;
private const double wmvWidth = 640d;
private const double wmvHeight = 480d;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Uri source = value as Uri;
if (source != null)
{
if (source.AbsolutePath.EndsWith(".wmv"))
{
return (parameter as string) == "Width" ? wmvWidth : wmvHeight;
}
// more media types ...
}
return (parameter as string) == "Width" ? defaultWidth : defaultHeight;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
一种解决方案是将 绑定ComboBox
到自创建MediaTypeDefinition
类的列表。
public class MediaTypeDefinition
{
public string Name { get; set; }
public int Height { get; set; }
}
然后,您可以将 绑定SelectedItem
到媒体元素的高度。
<ComboBox x:Name="mediaTypeList" ItemsSource="{Binding Definitions}" SelectedValuePath="Name" />
<MediaElement Height="{Binding SelectedItem.Height, Elementname=mediaTypeList}" />