Problem with UserControl with custom Dependency Property

Posted by Mathias Koch on Stack Overflow See other posts from Stack Overflow or by Mathias Koch
Published on 2010-06-16T11:23:57Z Indexed on 2010/06/16 11:32 UTC
Read the original article Hit count: 293

Filed under:
|
|
|
|

Hi,

I'm writing a user control with a dependency property for a search text called SearchText. It is a dependency property because I want to allow consumers of the control to use data binding. The user control contains a WPF TextBox where the user can enter the search text.

I could use data binding to connect the SearchText dependency property of the user control with the Text dependency property of the TextBox, but this binding only fires when the text box looses input focus. What I want is SearchText to be updated after every change of Text. So I have added a TextChanged event handler to the user control where I set SearchText to the value of Text.

My Problem is, the SearchText binding doesn't work, the source never gets updated. What am I doing wrong?

Here's the relevant part of the user controls code-behind:

public partial class UserControlSearchTextBox : UserControl
{
    public string SearchText
    {
        get { return (string)GetValue(SearchTextProperty); }
        set { SetValue(SearchTextProperty, value); }
    }

    public static readonly DependencyProperty SearchTextProperty =
        DependencyProperty.Register("SearchText", typeof(string), typeof(UserControlSearchTextBox), new UIPropertyMetadata(""));

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        SearchText = ((TextBox)sender).Text;
    }
    ...
}

The window that contains an instance of the user control has its DataContext set to an object that has a property also called SearchText.

<uc:UserControlSearchTextBox SearchText="{Binding SearchText}" />

The data context of the Window:

public class DataSourceUserManual : DataSourceBase
{
    private string _searchText;
    public string SearchText
    {
        get { return _searchText; }
        set
        {
            _searchText = value;
            ...
            OnPropertyChanged("SearchText");
        }
    }
}

Unfortunately, this setter is not called when I type into the text box. Any ideas?

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf