0

I'm not sure how to set a child control's viewmodel property from the parent. Below I'm trying to access IntValue, but I get an error saying it doesn't exist in the user control. That's because it exists in the viewmodel that is tied to the user control.

ChildViewModel.cs

public class ChildViewModel : ViewModelBase
{
    public ChildModel Model { get; private set; }

    public int IntValue
    {
        get
        {
            return Model.IntValue;
        }
        set
        {
            Model.IntValue = value;
            OnPropertyChanged();
        }
    }

    public ChildViewModel()
    {
        Model = new ChildModel();
    }
}

ParentControl.xaml

<UserControl
    x:Class="EmbeddedControls.ParentControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:EmbeddedControls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">

    <Grid>
        <local:ChildControl IntValue="4">
    </Grid>
</UserControl>

So what I would like to do here is to update the IntValue inline when creating the control in xaml. Is there a way to do this? Thanks in advance.

tldragoon
  • 109
  • 5
  • Smells like you're going down the wrong path. Read this answer https://stackoverflow.com/a/44729258/1228 and make sure you're not making that same mistake. Your DataContext should flow through the visual tree without you having to do anything other than design your view models correctly. –  Dec 05 '17 at 21:24

1 Answers1

0

There are some ways to achieve that:

  • Declare a Dependency property in your user control. Here you can find an example.
  • Communicate both ViewModels, here you can find some examples.

I hope this can help you.

ganchito55
  • 3,559
  • 4
  • 25
  • 46