面向云技术架构 - 痴者工良

  • 首页
  • 工良写的电子书
    • Istio 入门教程
    • kubernetes 教程
    • 从 C# 入门 Kafka
    • 多线程和异步
    • 动态编程-反射、特性、AOP
    • 表达式树
  • 本站文章导航
  • 隐私政策
愿有人陪你颠沛流离
遇到能让你付出的事物或者人,都是一种运气。
能遇到,就该珍惜。或许你们最终没能在一起,但你会切实地感受到力量。
正因为这样,那段相遇才变得有价值,才没有辜负这世间的每一段相遇。
  1. 首页
  2. .NET
  3. 正文

WPF 中 Webview2 如何修改数据存储目录

2023年9月14日 80点热度 0人点赞 0条评论
内容纲要

默认 Webview2 会被安装到系统目录,可能会导致程序启动时权限不足,无法使用 Webview2,以及多版本程序之间发生存储目录冲突。
因此需要自定义设置 Webview2 目录,最好就存储在程序安装目录下。

首先修改 App.xaml 文件,添加一行:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ui:ThemesDictionary Theme="Light" />
                <ui:ControlsDictionary />
            </ResourceDictionary.MergedDictionaries>
            <!--修改 WebView2 -->
            <wv2:CoreWebView2CreationProperties x:Key="EvergreenWebView2CreationProperties" />
        </ResourceDictionary>
    </Application.Resources>

然后在程序启动时,修改目录位置。

            // 配置 webview2 数据存放位置
            var p = Application.Current.Resources["EvergreenWebView2CreationProperties"] as CoreWebView2CreationProperties;
            p!.UserDataFolder = GetWebView2UserDataFolder();
        // 配置 webview2 用户数据目录
        private static string GetWebView2UserDataFolder()
        {
            var applicationName = "当前程序的名称";
            var result = System.IO.Path.Combine("{程序安装目录}/localdata", $"{applicationName}.WebView2");

            return result;
        }

然后在使用 Webview2 的窗口,配置控件的属性。

                <Grid>
                    <wv2:WebView2 x:Name="webView" Source="http://localhost:666"
                              CreationProperties="{StaticResource EvergreenWebView2CreationProperties}" Margin="0,0,0,0" />
                </Grid>

如果使用的是 BlazorWebview ,那么可以绑定初始化事件,在初始化之前设定目录。

            InitializeComponent();
            this.webView.BlazorWebViewInitializing += (s, e) =>
            {
                e.UserDataFolder = "D:/xxxxxx";
            };
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: webview wpf 修改 存储 目录
最后更新:2023年9月19日

痴者工良

高级程序员劝退师

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2023 whuanle.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

粤ICP备18051778号

粤公网安备 44030902003257号