CSS覆盖在WP8中不起作用

时间:2013-11-03 19:35:54

标签: c# windows-phone-8 windows-phone-8-sdk

我刚刚开始使用WP8开发,我已经遇到了第一个问题:我已经按照How to create your first app for Windows Phone教程进行操作,现在我已经跟着another tutorial尝试覆盖浏览器的CSS 。当我运行应用程序时,CSS不会更改,我只看到原始网页。

CSS文件名为mobile.css,可在Resources文件夹中找到。它的内容很简单

body {

background-color: blue;

}

这些是它的属性:

enter image description here

到目前为止,(非常简单的)应用代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MiniBrowser.Resources;
using System.IO;
using System.Windows.Resources;

namespace MiniBrowser
{
public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void Go_Click(object sender, RoutedEventArgs e)
    {
        string site = URL.Text;
        MiniBrowser.Navigate(new Uri(site, UriKind.Absolute));
    }

    private void BrowserLoadCompleted(object sender, NavigationEventArgs e)
    {
        ApplyStyleSheet("mobile.css");

        VisualStateManager.GoToState(this, "Loaded", true);
    }

    private void ApplyStyleSheet(string cssFilename)
    {
        //var sr = Application.GetResourceStream(new Uri(cssFilename, UriKind.Relative));
        StreamResourceInfo sr = Application.GetResourceStream(new Uri("/MiniBrowser;component/Resources/mobile.css", UriKind.Relative));
        using (var strm = sr.Stream)
        using (var reader = new StreamReader(strm))
        {
            string css = reader.ReadToEnd().Replace("\r", "").Replace("\n", "");

            var scriptToRun =
                "(function() {" +
                "  var pa= document.getElementsByTagName('head')[0] ; " +
                "  var el= document.createElement('style'); " +
                "  el.type= 'text/css'; " +
                "  el.media= 'screen'; " +
                "  el.styleSheet.cssText= '" + css + "'; " +
                "  pa.appendChild(el); " +
                "})();";
            MiniBrowser.InvokeScript("eval", scriptToRun);
        }
    }
}
}

其他一切正常:浏览器显示并正确加载页面。唯一的问题是mobile.css文件似乎被忽略了。

1 个答案:

答案 0 :(得分:0)

将css文件添加为资源:

windows phone css as resource

使用以下代码获取内容:

StreamResourceInfo sr = Application.GetResourceStream(new Uri("/YourAppName;component/Resources/Custom.css", UriKind.Relative));