I am trying to set twoway binding on a UserControl that I have created.
When I use the control in Xaml is set the DataContext like so…
<uc:MyUserControl DataContext="{Binding Path=MyObject, Mode=TwoWay}" />
My user control is defined as the following….
<UserControl x:Class="SilverlightApplication1.XText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="Text" Text="{Binding}"/>
</Grid>
</UserControl>
The data is displayed correctly, however if I make I change I wanted it to update with TwoWay binding.
I have tried this below, but it errors at runtime since no Path is defined.
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="Text" Text="{Binding Mode=TwoWay}"/>
</Grid>
</UserControl>
Any ideas on how to get the control inside the usercontrol to twoway bind to the DataContext?
I have found a solution that doesn’t require you to give a name to the base control.
When I defined a name for the base UserControl it was creating issues for me when I was adding multiple instances to my Grid, since they were defined as the same name.
This is a combination of my first answer and Doug’s answer.
Note the UserControl lacks the name property and the TextBox has no Binding declared in the XAML
XAML
CodeBehind
When you are ready to use it do the following