I have the following sample code in WPF. It is working well when I put the xaml and corresponding C# code inside windows, but when I am using a user control, the databinding doesn’t work. why?
Here is the code:
User control XAML:
<UserControl x:Class="TestWpf.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ec="clr-namespace:TestWpf"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="MainGrid" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<WrapPanel HorizontalAlignment="Right" VerticalAlignment="Stretch" Grid.Row="0" >
<Button Content="Edit" HorizontalAlignment="Right" Name="editButton1" VerticalAlignment="Stretch" Click="button1_Click" />
</WrapPanel>
<Grid x:Name="patientDataGrid" Margin="10,10,10,10" Grid.Row="1">
<Grid.Resources>
<Style TargetType="TextBox" >
<Setter Property="IsEnabled" Value="{Binding Path=IsEditing, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ec:UserControl1}}}" />
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox x:Name="textBox1" Grid.Column="0" Text="!234" />
<TextBox x:Name="textBox2" Grid.Column="1" />
</Grid>
</Grid>
</UserControl>
The user control C# code:
public partial class UserControl1 : UserControl
{
public static readonly DependencyProperty IsEditingProperty = DependencyProperty.Register(
"IsEditing", typeof(Boolean), typeof(MainWindow), new PropertyMetadata(false));
public Boolean IsEditing
{
get { return (Boolean)GetValue(IsEditingProperty); }
set { SetValue(IsEditingProperty, value); }
}
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
IsEditing = !IsEditing;
}
}
MainWindows XAML:
<Window x:Class="TestWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ec="clr-namespace:TestWpf"
Title="MainWindow" Height="200" Width="525">
<ec:UserControl1 x:Name="c" />
</Window>
I notice that if I move all C# and xaml code from user control to MainWindows, the binding is working without any problem.
What is wrong with the code?
You registered the dependency property to be owned by
MainWindowinstead of your UserControl.