ChrisRoo
ChrisRoo

Reputation: 15

How can I bind two user controls together?

I'm stuck in a problem right now and I think I'm lost. My project (C# WPF MVVM) consists of the following components (no framework):

Both user controls are loaded into the shell view and displayed there.

How can I now connect the ResultDisply with the property of the MainView.

I've tried setting the Data.Context of the DisplayView to the MainViewModel and binding its label to the MainViewModel's property (ResultOutput). When setting the autoproperty (1234) it works and 1234 is displayed. But everything that changes during runtime is no longer displayed. I've already thought about DependensyProperty, but I can't implement it.

MainViewModel: `

private string resultOutput = "1234";

        public string ResultOutput
        {
            get { return resultOutput; }
            set 
            { 
                resultOutput = value; 
                OnPropertyChanged("Result");
            }
        }


        private void AddTwoNumbers()
        {
            int result = Num1 + num2;
            ResultOutput = result.ToString();
        }

DisplayView:

<UserControl.DataContext>
        <viewModel:MainViewModel />
    </UserControl.DataContext>
    <Grid>
        <Label x:Name="ResultTB"
               Content="{Binding ResultOutput}"
                   Background="#333"
                   Foreground="LightGray"
                   FontSize="40"
                   HorizontalContentAlignment="Left"
                   VerticalContentAlignment="Bottom"
                   Padding="8,0,0,5" />

    </Grid>
</UserControl>

` I hope someone can help me out of the darkness. :-)

Upvotes: 0

Views: 158

Answers (1)

GeorgeKarlinzer
GeorgeKarlinzer

Reputation: 596

<UserControl.DataContext>
        <viewModel:MainViewModel />
</UserControl.DataContext>

This is wrong approach, because you create new instance of MainViewModel.

I've had the same problem, solution (without DependencyProperty) that works for me is to place your UserControl inside container (for example StackPanel) and bind DataContext of this container.

class ShellViewModel
{
    public MainViewModel MainViewModel { get; }

    public ShellViewModel()
    {
        MainViewModel = new MainViewModel();
    }
}
<Window x:Class="ShellView" ...>
     <StackPanel DataContext="{Binding MainViewModel}">
         <MainView/>
         <ResultDisplay/>
     </StackPanel>
</Window>

So now MainView and ResultDisplay have the same ViewModel object

Upvotes: 1

Related Questions