【问题标题】:Binding Source-Property of MediaElement to FileInfo将 MediaElement 的源属性绑定到 FileInfo
【发布时间】:2011-08-28 16:27:51
【问题描述】:

我有一个视图模型类,它提供 FileInfo 类型的属性 MediaFile,我想将该属性绑定到 MediaElement 的 Source 属性。

问题在于,MediaElement 的 Source 属性需要一个 Uri,但我无法访问 FileInfo 类的 FullName 属性(在绑定中定义的转换器中),因为这将引发 SecurityException。

图像没有问题,因为 Image 控件需要一个 ImageSource 对象,我可以使用 FileInfo 实例的流在转换器中创建该对象。

如何定义绑定,以便我的 MediaElement 获得正确的来源?或者我如何将 MediaElement 传递给转换器,以便我可以在 MediaElement 上调用 SetSource(Stream)。

ViewModel:

public class ViewModel {
  // additional code omitted
  public FileInfo MediaFile {get; set;}
}

转换器:

public class FileInfoToMediaConverter : IValueConverter {
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        var file = value as System.IO.FileInfo;
        if (MediaResourceFactory.IsImage(file.Extension)) {
            System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
            image.SetSource(file.OpenRead());
            return image;
        }
        else if (MediaResourceFactory.IsVideo(file.Extension)) {
           // create source for MediaElement
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        throw new NotImplementedException();
    }
}

绑定:

    <Image Source="{Binding MediaFile, Converter={StaticResource fileInfoToMediaConverter} }"/>
    <MediaElement Source="{Binding MediaFile, Converter={StaticResource fileInfoToMediaConverter}}/>

【问题讨论】:

    标签: c# silverlight data-binding silverlight-4.0 mvvm


    【解决方案1】:

    您是否用尽了具有提升权限的浏览器?否则,您将无法访问本地文件系统,并且您将收到安全异常。即使具有提升的权限(我的文档、我的图片等),您仍将受限于您有权访问的目录。

    假设您是具有提升权限的 OOB,您可以执行以下操作:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    {
        var file = value as System.IO.FileInfo;
        if (MediaResourceFactory.IsImage(file.Extension)) {
            System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
            image.SetSource(file.OpenRead());
            return image;
        }
        else if (MediaResourceFactory.IsVideo(file.Extension)) {
           // create source for MediaElement
           return new Uri(file.FullName).AbsoluteUri;
        }
        return null;
    }
    

    【讨论】:

    • 感谢您的回答。该应用程序正在浏览器内运行,因此无法访问 FullName。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多