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



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

我试着这样做,认为它将更符合mvvm - ViewModel不必知道整个视图,以便使用这个组件。但我认识到,在ViewModel中定义XAML元素仍然不符合MVVM的精神。但在这一点上,我只想知道这种技术是否可行。

我知道我可以在ViewModel中定义一个属性,然后将其绑定到视图中定义的XAML元素的属性

。例如,在ViewModel中定义一个字符串,并将其绑定到TextBlock XAML元素的Text属性。但是,是否有可能在ViewModel中简单地定义XAML元素本身,并在视图的XAML标记中使用它?示例代码。我正在使用c++/WinRT与WinUI 3:

MainWindowViewModel.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标记中使用它?

是的,这将是工作。

我在WinUI3 c#中测试了它,代码运行良好。

最新更新