0





15

Advertisement

We're using Prism with UWP, and have a UserControl which we want to display several times in a Grid (each instance relating to a connected user).

If the UserControl were a Page, I know of course that the code can/should go in associated ViewModel. What's the equivalent for the UserControl? I obviously want to keep my code DRY, and call the same code for each UserControl instance.

My research is pointing me towards a Dependency Property, but I haven't found a clear example of how I should implement it.

Note that the UserControl needs to display data and also implement Buttons with associated Commands on the ViewModel.

Question author James-lavery | Source

Advertisement


0


Create a separate view model

You could create a view model specifically for the user control. The DataContext of the user control would be set to an instance of this view model. You can expose commands and data related to each user in the view model and bind to them in the user control, just like you would if it were a page.

This scenario works best if the user control can function independently of the page it is in. If you need the user control VM to communicate to the page VM, then you'll need to facilitate this somehow between the VMs (maybe the user control VM can take a reference to the page VM as a dependency upon construction).

Expose command properties in the user control

Another way is to create dependency properties for each command you want to expose in the user control, which can then be bound to in the page's 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));
}

Now you can bind to DeleteCommand on the user control.


Typically I use some combination of both of these methods when I use user controls.

Answer author Decade-moon