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

WinUI/UWP XAML中如何统一绑定特定ViewModel到View?

在WinUI或UWP XAML中,如何将特定类型的ViewModel统一绑定到特定View?

这是《UserControl应暴露任意属性还是仅ViewModel?》的后续问题。

示例

例如,我们来看Material UI中的这个基础卡片:

基础卡片

根据《UserControl应暴露任意属性还是仅ViewModel?》中的建议,我制作了如下控件:

<Card
    Subtitle="Word of the Day"
    Title="Be*nev*o*lent"
    LowerSubtitle="adjective"
    Description="well meaning and kindly. 'a benevolent smile'"
    LinkText="Learn more"
    LinkUri="http://example.com" />

我还了解到团队会频繁将此Card与特定ViewModel——WordOfTheDayViewModel配合使用:

runtimeclass WordOfTheDayViewModel: Windows.UI.Xaml.Data.INotifyPropertyChanged
{
    WordOfTheDayViewModel();
    String Word{ get; };
    String PartOfSpeech{ get; };
    String Definition{ get; };
    Uri DefinitionUri{ get; };
}

绑定方式如下:

<Card
    Subtitle="Word of the Day"
    Title="{x:Bind ViewModel.Word}"
    LowerSubtitle="{x:Bind ViewModel.PartOfSpeech}"
    Description="{x:Bind ViewModel.Definition}"
    LinkText="Learn more"
    LinkUri="{x:Bind ViewModel.DefinitionUri}" />

在这个假设场景中,这种绑定会在多处重复出现——我们需要在很多地方展示绑定到同类型ViewModel(不同实例)的卡片。能否编写代码来标准化这种绑定,让团队无需每次都重写这7行代码?

潜在解决方案

据我所知,有几种潜在方案,但不确定该如何选择:

  • 不标准化绑定:让团队每次使用时都将WordOfTheDayViewModel绑定到Card。“实际重复代码的次数可能比你想象的少,且每次绑定可能都会有必要的细微差异。”
  • 创建另一个UserControl:创建一个新的UserControl,比如<WordOfTheDayCard Word="">,它接收WordOfTheDayViewModel并在后台完成绑定。“这种情况下新增UserControl的开销不大(?)。”
  • 函数式绑定方法:在React中,我只需编写一个转换函数,将WordOfTheDayViewModel映射为格式规范的Card(见下方示例)。开销很简单:多一次函数调用。“WinUI也能做到,只是你不知道而已。”
  • 在ResourceDictionary中使用标准ItemTemplate:不确定这是否可行?
  • 其他方案:欢迎提出!

(以下是我在React中的写法):

// wow, so cheap! much virtual DOM
function WordCard(word: WordOfTheDayViewModel): JSX.Element {
    return <Card
        Subtitle="Word of the Day"
        Title={word.Word}
        LowerSubtitle={word.PartOfSpeech}
        Description={word.Definition}
        LinkText={"Learn more"}
        LinkUri={word.DefinitionUri}>;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:44:54