繁体   English   中英

我可以在 ViewModel 中定义一个 XAML 元素并使用 C++/WinRT 和 WinUI 3 直接在视图中使用它吗?

[英]Can I define a XAML element in the ViewModel and use it directly in the View using C++/WinRT and WinUI 3?

关于在 ViewModel 中使用 View 中的 XAML 元素,已经提出了很多问题。 但是如何在 ViewModel 中定义一个 XAML 元素并在 View 的 XAML 标记中使用它呢? 这样 ViewModel 从一开始就知道该元素(并拥有该元素)。

我在尝试这样做时认为它会更符合 MVVM——ViewModel 不必了解整个 View 就可以使用该组件。 但我认识到在 ViewModel 中定义 XAML 元素仍然不符合 MVVM 的精神。 但在这一点上,我只想知道这种技术是否可行。

我知道我可以在 ViewModel 中定义一个属性,然后将其绑定到 View 中定义的 XAML 元素的属性 例如,在 ViewModel 中定义一个字符串并将其绑定到 TextBlock XAML 元素的 Text 属性。 但是是否可以简单地在 ViewModel 中定义 XAML 元素本身并在 View 的 XAML 标记中使用它?

示例代码。 我在 WinUI 3 中使用 C++/WinRT:

主窗口视图模型.idl

namespace MyApp
{
    runtimeclass FooViewModel
    {
        MainWindowViewModel();
        Int32 IntProperty; // I can bind this to a XAML element's property
        Microsoft.UI.Xaml.Controls.Frame Frame; // Can I use this in the View?
    }
}

MainWindow.idl (视图)

import "ViewModel/MainWindowViewModel.idl";
namespace MyApp
{
    runtimeclass MainWindow : Micorosoft.UI.Xaml.Window
    {
        MainWindow();
        MainWindowViewModel MainWindowViewModel{ get; };
    }
}

MainWindow.xaml (视图的 XAML)

<Window
    x:Class="MyApp.MainWindow"
    //...
    >

    <StackPanel>
        // I can bind to a property of MainWindowViewModel as such:
        <Slider Minimum="0" Maximum="{x:Bind MainWindowViewModel.IntProperty}" />

        // Is there a way to use the Frame defined in MainWindowViewModel here, or can you only create a new Frame instance?
        <Frame/>
    </StackPanel
</Window>

是否可以简单地在 ViewModel 中定义 XAML 元素本身并在 View 的 XAML 标记中使用它?

是的,这将是工作。

我在 WinUI3 C# 中测试过,代码运行良好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM