Mort
Mort

Reputation: 150

Binding to other control's view model

I'm attempting to bind to a property inside the ViewModel of a contained control, but it seems that WPF won't allow me to bind to the property. When trying to do so, it reports the error: ViewModel is not supported in a Windows Presentation Foundation (WPF) project.

Is there any way for me to bind to a property in the ViewModel, using XAML, or do I have to perform all my ViewModel modifications in code behind?

Main window XAML:

<Window x:Class="MyNamespace.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MyNamespace"
    mc:Ignorable="d"
    Title="MainWindow">
<Grid>
    <!-- Error: Can't bind to ViewModel.MyValue -->
    <local:UserControl1 ViewModel.MyValue="123"/>
</Grid>

User control class:

public partial class UserControl1 :UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        ViewModel = new UserControlViewModel();
    }

    public UserControlViewModel ViewModel
    {
        get
        {
            return (UserControlViewModel) GetValue(ViewModelProperty);
        }
        set
        {
            SetValue(ViewModelProperty, value);
        }
    }

    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(UserControlViewModel), typeof(UserControl1), new PropertyMetadata(null));
}

User Control's View Model class:

public class UserControlViewModel
{
    public string MyValue
    {
        get;
        set;
    }
}

Upvotes: 0

Views: 49

Answers (1)

mm8
mm8

Reputation: 169190

No, you cannot use XAML to set a nested property of a dependency property of a control:

Can I use XAML to set a nested property (property of the value of a property) of a control?

You can only set the value of the property itself:

<local:UserControl1>
    <local:UserControl1.ViewModel>
        <local:UserControlViewModel MyValue="123" />
    </local:UserControl1.ViewModel>
</local:UserControl1>

Upvotes: 1

Related Questions