带有 Prism 的 UWP - 在页面上处理多个 UserControl 实例

UWP with Prism - handling more than one instance of UserControl on a Page

我们将 Prism 与 UWP 一起使用,并且有一个我们希望在网格中多次显示的 UserControl(每个实例都与连接的用户相关)。

如果 UserControl 是一个页面,我当然知道代码 can/should 进入关联的 ViewModel。 UserControl 的等价物是什么?我显然想让我的代码保持干燥,并为每个 UserControl 实例调用相同的代码。

我的研究指向依赖关系 属性,但我还没有找到应该如何实现它的明确示例。

注意UserControl 需要显示数据并且在 ViewModel 上实现带有关联命令的按钮。

创建单独的视图模型

您可以专门为用户控件创建一个视图模型。用户控件的 DataContext 将设置为此视图模型的一个实例。您可以在视图模型中公开与每个用户相关的命令和数据,并在用户控件中绑定到它们,就像在页面中一样。

如果用户控件可以独立于它所在的页面运行,则此方案效果最佳。如果您需要用户控件 VM 与页面 VM 通信,则需要以某种方式在 VM 之间促进此操作(也许用户控制 VM 可以将对页面 VM 的引用作为构造的依赖项。

在用户控件中公开命令属性

另一种方法是为每个要在用户控件中公开的命令创建依赖属性,然后可以将其绑定到页面的 XAML.

<UserControl>
    <Grid>
        <Button Content="Delete" Command="{x:Bind DeleteCommand}"/>
    </Grid>
</UserControl>
public sealed partial class MyUserControl : UserControl
{
    public ICommand DeleteCommand
    {
        get { return (ICommand)GetValue(DeleteCommandProperty); }
        set { SetValue(DeleteCommandProperty, value); }
    }

    public static readonly DependencyProperty DeleteCommandProperty =
        DependencyProperty.Register("DeleteCommand", typeof(ICommand), typeof(MyUserControl), new PropertyMetadata(null));
}

现在您可以绑定到用户控件上的 DeleteCommand


在使用用户控件时,我通常会结合使用这两种方法。