I have a user control which implements INotifyPropertyChanged and has a property SelectedTopicDescription and I am trying to bind a textbox Text property to this public property. I know the property is changing however the textbox is not being updated.
I have tried a number of things and I know this should be easy.
I have tried using the following datacontext within the UserControl xaml but it had no effect. I have read about dependency properities but shouldn't i be able to do this by using INotifyPropertyChanged?
Your help is appreciated.
DataContext="{Binding RelativeSource={RelativeSource Self}}"
public partial class CodePage : UserControl ,INotifyPropertyChanged{
private string _selectedTopicDescription = string.Empty;
public string SelectedTopicDescription {
get { return _selectedTopicDescription; }
set {
_selectedTopicDescription = value;
OnPropertyChanged("SelectedTopicDescription");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string property) {
PropertyChangedEventHandler ph = this.PropertyChanged;
if (ph != null)
ph(this, new PropertyChangedEventArgs(property));
}
…
The textbox is..
Width="200" Margin="141,142,0,153"
Text="{Binding SelectedTopicDescription}"
HorizontalAlignment="Left">
Best Answer
It's probably not a good idea to fiddle around with
DataContext
when binding elements in a Usercontrol with properties of the that UserControl. Instead direct the binding to the UserControl via theElementName
property ofBinding
, like this:-This uses the fact that the
Content
element in the user control is has the name "LayoutRoot" and that in turn being aFrameworkElement
has aParent
property which will be theUserControl
.