I have a main form, it has a model of this form in the DataContext . In this model, there is a property that refers to another model. I want to attach a specific form element to the context of the model itself, which is in the property. I tried to write DataContext={Binding anotherModel} , it does not help. even if you use Mode=TwoWay .

Model:

 public static MainWindow instance; // статическая ссылка на объект MainWindow private static MyClass _anotherModel = null; // внутренне хранилище значения public static MyClass anotherModel // обработчик изменения значения { get => _anotherModel; set { if (_anotherModel == value) return; _anotherModel = value; instance.PropertyChanged?.Invoke(instance, new PropertyChangedEventArgs("anotherModel ")); } } 

Form Item:

 <TabControl x:Name="Tabs" DataContext="{Binding anotherModel, Mode=TwoWay}"></TabControl> 

When I check the DataContext this item through a dynamic visual tree , it says BindingExpression and cannot be viewed.

Interesting fact: If you assign a reference to a model to this property before initializing the components, it will be displayed in the inspector and can be viewed.

  • 3
    And why is the property static? - Andrey NOP
  • Mode=TwoWay - this detective allows not only to read but also to write a variable, it has no direct relation to your problem. - NewView
  • The problem of the author is that he is trying to bind a static property in a way that is suitable only for instance ones. In addition, some crutch with a static instance trying to fasten, which does not work. - Andrey NOP
  • I have a static property, because I need to get it from other forms. I also have a static ObservableCollection , but the binding to it is successful. - Puro
  • You, like, put the MVVM tag, but in fact you have the data in the view, hence your crutches with static. But this does not work for the reason that by calling instance.PropertyChanged?.Invoke you tell the framework that you have updated the property "anotherModel " in the instance instance , but it does not have such a property, it is static and does not belong to any instance. - Andrey NOP

1 answer 1

When I made the property non-static and started calling PropertyChanged directly from the model itself (instead of calling it from the instance ), it all worked.

It was:

 private static MyClass _anotherModel = null; public static MyClass anotherModel { get => _anotherModel; set { if (_anotherModel == value) return; _anotherModel = value; instance.PropertyChanged?.Invoke(instance, new PropertyChangedEventArgs("anotherModel")); } } 

It became:

 private MyClass _anotherModel = null; public MyClass anotherModel { get => _anotherModel; set { if (_anotherModel == value) return; _anotherModel = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("anotherModel")); } }