WPF: Cannot bind to a custom controls dependency property
I've created a custom control with a dependency property for databinding.
The binded value should then be displayed in a text box. This binding
works properly.
The problem occurs when I implement my custom control. The grid's data
context is a simple view model which contains a String property for
binding.
If I bind this property to a standard wpf controls text box everything
works fine.
If I bind the property to my custom control nothing happens.
After some debugging I found out that SampleText is searched in
CustomControl. Of course it doesn't exist there. Why is my property
searched in CustomControl and not taken from the DataContext as it happens
in scenario 1.
<Window x:Class="SampleApplicatoin.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.DataContext>
<controls:ViewModel/>
</Grid.DataContext>
<TextBox Text="{Binding SampleText}"/>
<controls:CustomControl TextBoxText="{Binding SampleText}"/>
</Grid>
</Window>
Below the XAML code of the custom control. I use DataContext = Self to get
the dependency property from code behind:
<UserControl x:Class="SampleApplication.CustomControl"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23"
Margin="87,133,0,0" TextWrapping="Wrap" Text="{Binding
TextBoxText}" VerticalAlignment="Top" Width="120"/>
</Grid>
</UserControl>
The xaml.cs file just contains the dependency property:
public partial class CustomControl : UserControl
{
public static readonly DependencyProperty TextBoxTextProperty =
DependencyProperty.Register("TextBoxText", typeof (String), typeof
(CustomControl), new PropertyMetadata(default(String)));
public CustomControl()
{
InitializeComponent();
}
public String TextBoxText
{
get { return (String) GetValue(TextBoxTextProperty); }
set { SetValue(TextBoxTextProperty, value); }
}
}
Thanks for any help on this. It really drives me crazy now.
Are you trying to make cash from your visitors with popup ads?
ReplyDeleteIn case you do, have you ever used Propeller Ads?