0

I have a project solution as below

solution with different project in MVVM

The Start Window is MainWindowStart.xaml located in ProjectStart.View with Datacontext ProjectStartViewModel.cs.

MainWindowStart.xaml includes 2 UserControls (MyUC1.xaml, MyUC2.xaml) that are located in a different project (Project1) with DataContext Project1ViewModel.cs as showen. The properties are correctly binded on InitializeComponent() of MainWindow but not working when the property change. It works fine when the user controls are included in a window that is located in a some project of user control

This is the code of Property in a ViewModel ViewModel

 private int _IndexTabMain;

    public int IndexTabMain
    {
        get { return _IndexTabMain; }
        set
        {
            if (_IndexTabMain != value)
            {
                _IndexTabMain = value;
                this.RaisePropertyChanged("IndexTabMain");
            }

        }
    }

and this is the code of property binded in MyUC2.xaml that is notified from a selection change in MyUC1.xaml

  <TextBlock Text="{Binding DataContext.IndexTabMain, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}">

In advance thank you Manuel

Manuel
  • 11
  • 4
  • As a general rule, you should never explicitly set the DataContext of a UserControl. Doing so effectively prevents that a DataContext is inherited from the parent control or window, which usually breaks your Bindings. See e.g. here: http://stackoverflow.com/a/28982771/1136211 – Clemens Apr 21 '17 at 08:31
  • Where is the IndexTabMain property defined? – mm8 Apr 21 '17 at 08:48
  • Your UserControl should expose DependencyProperties on their surface to which you bind your ViewModel. Just like a TextBox has a Text property, your user control should have a Whatever property that is bound to your view model's Whatever property. –  Apr 21 '17 at 16:31

1 Answers1

0

If IndexTabMain is defined in the view model of the parent window, you should set the AncestorType property to Window:

<TextBlock Text="{Binding DataContext.IndexTabMain, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=Window}}">
mm8
  • 163,881
  • 10
  • 57
  • 88