You could bind different DataContexts to different controls.
A control cannot be bound to multiple different DataContexts. ( A control can only have one object set to its DataContext property.) For more information, you could refer here.
However, the binding does not have to be bound to its DataContext. You can use other binding properties to specify a different source for the binding. Common properties for changing binding sources are Source, RelativeSource, and ElementName. You can refer here for more details.
- You can only change the binding source for a specific binding, like you did in the Command binding.
- Alternatively, you can change it for the entire control by setting or binding the control's DataContext property to something else.
MainWindow.xaml:
<Window.Resources>
<local:MainViewModel x:Key="mvm"/>
</Window.Resources>
<Grid DataContext="{StaticResource mvm}" >
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid x:Name="grid1" Background="AliceBlue" Height="100" DataContext="{Binding VM1}" >
<TextBlock VerticalAlignment="Top" Foreground="Black" Background="White" HorizontalAlignment="Left" Text="{Binding String1}" Width="100" Height="40">
<TextBlock.ToolTip>
<!--<TextBlock Background="White" Foreground="Black" Width="100" Height="40" Text="{Binding ElementName=tb,Path= Text}"/>-->
<TextBlock>
<Run Text="{Binding Source={x:Reference tb}, Path=Text}" FontWeight="Bold"/>
</TextBlock>
</TextBlock.ToolTip>
</TextBlock>
<TextBlock Background="White" Foreground="Black" Width="100" Height="40" Text="{Binding ElementName=tb,Path=DataContext.String2}"/>
</Grid>
<Grid x:Name="grid2" Grid.Row="1" Background="LightGreen" Height="100" DataContext="{Binding VM2}">
<TextBlock x:Name="tb" VerticalAlignment="Top" Foreground="Black" Background="White" HorizontalAlignment="Left" Text="{Binding String2}" Width="100" Height="40"/>
</Grid>
</Grid>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class MainViewModel
{
public ViewModel1 VM1{ get; set; }
public ViewModel2 VM2 { get; set; }
public MainViewModel()
{
VM1=new ViewModel1();
VM2=new ViewModel2();
}
}
public class ViewModel1
{
public string String1 { get;set;} ="string1";
}
public class ViewModel2
{
public string String2 { get;set;}="string2";
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.
[5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html