I have a WPF application and want to share data between my MainWindow and one or more UserConrols, but for simplicity lets assume I have only one MainWindow.xaml and one UserControl.xaml. From what I've gathered so far, this can be done with Bindings and Properties. So I tried this with no success.
The Object I want to share between the controls looks like this:
SharedObject {
prop string Name;
prop List<Product> Products;
}
Product {
prop string ItemName;
prop double Price;
prop bool Available;
}
So I load the SharedData in the MainWindow and want to be able to edit this in the UserControl, but in TwoWay mode, to get the modified product list updates also in the MainWindow. I also want to access and modify the Name Property of the SharedObject in the UserControl.
How can I achieve this? Is the Property/Binding the way to go? Can this state management also be done in a more elegant way? (in dotnet Core 3.1)
CodePudding user response:
You should set the DataContext
of the window to an instance of your view model (SharedObject
) and then let the UserControl
inherit the DataContext
from its parent window (which it does by default).
You can then bind directly to any public property of the view model from the an element in UserControl
.