You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

[UWP][C#]如何在ListBox的WebView中绑定显示文本

在UWP ListBox中嵌入WebView并绑定带HTML的数据库选项

我来帮你把这个需求落地,结合你给出的代码片段,先补全并解释完整的实现方案:

首先,你的核心需求是让ListBox的每个选项用WebView渲染带HTML标签的内容,并且选项数量和数据库记录一致,关键在于数据绑定和WebView的HTML加载逻辑。

1. 完整的XAML实现

先把你截断的XAML补全,重点是WebView如何绑定数据库模型的HTML内容:

<ListBox Name="ListOption" Grid.Row="4" 
         xmlns:m="using:KipinATM_Win10.Tryout.Models"
         SelectionChanged="ListAlternatives_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate x:DataType="m:DBOPTION">
            <!-- 每个ListBox项对应一个WebView,绑定到DBOPTION的HtmlContent属性 -->
            <WebView Width="Auto" Height="Auto"
                     NavigationCompleted="WebView_NavigationCompleted">
                <WebView.NavigateToString>
                    <Binding Path="HtmlContent" Mode="OneWay"/>
                </WebView.NavigateToString>
            </WebView>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

2. 后台代码与数据库数据绑定

要让ListBox自动同步数据库的选项数量,你需要用ObservableCollection作为数据源(它会自动通知UI更新),然后从数据库加载数据并绑定到ListBox:

using KipinATM_Win10.Tryout.Models;
using System.Collections.ObjectModel;
using Windows.UI.Xaml.Controls;

public sealed partial class YourPage : Page
{
    // 用ObservableCollection保证数据变化时UI自动更新
    private ObservableCollection<DBOPTION> _dbOptions = new ObservableCollection<DBOPTION>();

    public YourPage()
    {
        this.InitializeComponent();
        // 页面初始化时加载数据库数据
        LoadOptionsFromDbAsync();
        // 绑定数据源到ListBox
        ListOption.ItemsSource = _dbOptions;
    }

    private async void LoadOptionsFromDbAsync()
    {
        // 替换成你的数据库查询逻辑,比如从SQLite/EF Core读取所有选项
        var optionsFromDb = await YourDatabaseHelper.GetAllOptionsAsync();
        
        // 清空旧数据,添加新数据,ListBox会自动更新项的数量
        _dbOptions.Clear();
        foreach (var option in optionsFromDb)
        {
            _dbOptions.Add(option);
        }
    }

    private void ListAlternatives_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // 获取选中的选项模型
        var selectedOption = ListOption.SelectedItem as DBOPTION;
        if (selectedOption != null)
        {
            // 这里处理选中逻辑,比如获取选项ID、做业务操作
        }
    }

    private void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
    {
        // 可选:让WebView自动适应HTML内容的高度,避免内容被截断
        sender.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" }).Completed += (asyncSender, asyncArgs) =>
        {
            if (asyncArgs.Status == Windows.Foundation.AsyncStatus.Completed)
            {
                string contentHeight = asyncArgs.GetResults();
                sender.Height = double.Parse(contentHeight);
            }
        };
    }
}

3. 数据库模型的完善

你的DBOPTION模型需要包含存储HTML内容的属性,并且最好实现INotifyPropertyChanged(如果需要动态更新内容的话):

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace KipinATM_Win10.Tryout.Models
{
    public class DBOPTION : INotifyPropertyChanged
    {
        // 存储HTML内容的属性,对应数据库字段
        private string _htmlContent;
        public string HtmlContent
        {
            get => _htmlContent;
            set
            {
                if (_htmlContent != value)
                {
                    _htmlContent = value;
                    OnPropertyChanged();
                }
            }
        }

        // 其他数据库字段,比如选项ID、文本等
        public int OptionId { get; set; }

        // 实现INotifyPropertyChanged,保证属性变化时UI自动刷新
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

几个关键注意点

  • 性能考量:如果数据库中选项数量很多,多个WebView实例会占用较多资源。如果HTML内容不复杂,可以考虑用RichTextBlock结合HTML解析库替代,但WebView对复杂HTML的兼容性更好。
  • 安全防护:如果数据库中的HTML来自用户输入或不可信来源,一定要做XSS过滤,避免注入危险脚本。
  • 高度适配:默认WebView不会自动调整高度,上面的NavigationCompleted事件处理可以让WebView根据HTML内容高度自动调整,保证内容完整显示。

内容的提问来源于stack exchange,提问作者Rose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:21:16