0

I have a UserControl (MVVM pattern) and a MainWindow. The UserControl Model get all Data and hold it, now i want to access this data from the MainWindow and bind it to a Control.

But how?

EDIT

UserControl.cs:

public UserControl()
{
    InitializeComponent();
    DataContext = new ViewModel.UserControlViewModel(
                       new Model.UserControlModel(this.facade));
}

the ViewModel.cs (from UserControl.cs)

public string Status
{
    get { return _model.Status; }
    set
    {
        if (value == _model.Status)
        {
            return;
        }
            _model.Status = value;
            base.NotifyPropertyChanged();
        }
    } 

MainWindow.xaml

<StatusBarItem Grid.Column="1">
    <TextBlock x:Name="txtStatus" Text="{Binding Path=???,
                                    Mode=TwoWay,
                                    UpdateSourceTrigger=PropertyChanged}" />
</StatusBarItem>

So it's not so easy (maybe only for me ;) ) to set the DataContext for this

benba
  • 821
  • 9
  • 16
  • 1
    If your mainwindow hold the instance of UserControl, then you access all the members of ViewModel using DataContext property. If possible, put the requirements more clearly. – Jawahar Jul 30 '14 at 09:41
  • Can you please be more detailed? – rPulvi Jul 30 '14 at 09:43
  • The Data should be only updated by the UserControl, so i need to access this one instance of the ViewModel in the MainWindow. And this means, i couldn't set the DataContext in the MainView. – benba Jul 30 '14 at 10:14
  • While I accept that the 'duplicate' question is *not* an exact duplicate, it *does* provide a good solution for you to pass your data using `delegate`s, which are kind of like custom events, but far more versatile. Furthermore, it also links to another question with another example of using `delegate`s. You can use `delegate`s to pass data to and from children and parents of any kind. – Sheridan Jul 30 '14 at 10:15

1 Answers1

0

You could create a MainWindowViewModel which holds the data like so:

public class MainWindowViewModel {
    public AllDataType AllData {get;set;}
}

Now you bind the MainWindows DataContext to this ViewModel and access the data:

<MainWindow>
    <ctrl:UserControl DataContext="{Binding AllData}"/>
    <AnotherControl DataContext="{Binding AllData}"/>
</MainWindow>
Florian Gl
  • 5,984
  • 2
  • 17
  • 30