I have a WPF user control which uses a property from my viewmodel for binding. I now want to use two instances of that user control with the same viewmodel, but override the binding in one of them.
The code looks like this
User control
<UserControl x:Class="TestWpfApp.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWpfApp">
<Grid>
<DockPanel>
<Label Margin="10" Content="{Binding MyLabel}"/>
<Button Margin="10" Content="{Binding MyButton}"/>
</DockPanel>
</Grid>
</UserControl>
Main view
<Window x:Class="TestWpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWpfApp"
Title="MainWindow" Height="150" Width="525">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<DockPanel>
<local:UserControl1 DockPanel.Dock="Top" x:Name="UserControl1"/>
<!--In this instance of UserControl1, I want the Label to bind to the MyNewLabel-->
<local:UserControl1 DockPanel.Dock="Top" x:Name="UserControl2"/>
</DockPanel>
</Grid>
</Window>
Viewmodel
public class ViewModel
{
public string MyLabel => "Label1";
public string MyButton => "Button1";
public string MyNewLabel => "Label2";
}
In the second instance of UserControl1
, I would like the label to be bound to a different property. I tried setting that property as a resource on the user control, and then overriding it in the main view but I wasn't able to get that to work.
In reality, I'm using DevExpress controls and POCO viewmodels, if that makes things easier.