Reputation: 33
I have a button button_extract
. I want to bind it to two different data contexts (2 classes in different namespaces)
I want to set the Command and IsEnabled
properties to different data context.
I have one datacontext
set for Command property. But how to I specify the datacontext
of IsEnable
property which is in different class and namespace. Here is the scenario:-
I have a project named Environments with three namespaces:Viewmodel,Data and View Viewmodel has class A Data has class B View has xaml C with button button_extract.
The data context for C is set to class A.The xaml is as follows
<UserControl x:Class="Enviornment.Views.C"
DataContext="Environment.Viewmodel.A">
<Button Name="button_extract" Command="{Binding ExtractButtonClick}" IsEnabled="{Enviornment.B.SelectedEnvionment}" >Extract</Button>
The above code does not work. The binding of IsEnabled throws error. How can I set the datacontext of IsEnabled to that of Enviornment.B???
Upvotes: 0
Views: 1358
Reputation: 69959
You seem to have a common misconception about WPF regarding the need to set the DataContext
. In fact, there is rarely any need to set a DataContext
on any control as typically the Window
has had its DataContext
set and each control's DataContext
will automatically inherit from that.
So, how to data bind to two different places? Generally, one place would use a normal Binding Path
and the other would use a RelativeSource Binding Path
. However, that would be more for the case where you wanted to data bind to properties of the set DataContext
and properties of a control's code behind.
It is more common in your scenario to simply prepare a view model. That is a custom class that implements the INotifyPropertyChanged
interface and provides all of the properties and functionality that your Window
, UserControl
, or 'view' requires. You would then set an instance of this single object as the DataContext
.
Therefore, simply add properties of the relevant classes into your view model and then you will be able to access them all using the one single DataContext
object. Please search online for MVVM for further information.
Upvotes: 1