Click here to Skip to main content
15,914,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying out custom control that has a label for its header and a textbox for its InputText. The control binds fine but I can't seem toe get it to update on PropertyChanged event. Here is how I did the class:

C#
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header",typeof(string), typeof(CustomControl), new PropertyMetadata(null));
public static readonly DependencyProperty InputTextProperty = DependencyProperty.Register("InputText",typeof(string), typeof(CustomControl), new FrameWorkPropertyMetadata(null) {BindsTwoWayByDefault = true} );

public string Header
{
   get { return (string)GetValue(HeaderProperty); }
   set { SetValue(HeaderProperty,value; }
}


public string InputText
{
   get { return (string)GetValue(InputTextProperty); }
   set { SetValue(InputTextProperty,value; }
}


and here is the ControlTemplate:

XML
<StackPanel Orientation="Horizontal">
   <TextBlock Text="{Binding Header, RelativeSource={RelativeSource TemplatedParent}}" Margin="0,0,10,0"/>
   <TextBox Text="{Binding InputText, RelativeSource={RelativeSource TemplatedParent}}" MinWidth="150"/>
</StackPanel>


my call for the control looks like this:

XML
<local:CustomControl Header="HeaderText" InputText={Binding InputString, UpdateSourceTrigger=PropertyChanged/>


What did I miss?
Posted

What is your DataContext here? just implement INotifyPropertyChanged event for your properties present in the DataContext object.
 
Share this answer
 
Comments
Lyandor 31-Dec-15 3:04am    
Hi,

my data context is a public string property in a viewmodel called InputString. This code works if i change focus from the control. What I wanted was calling set on PropertyChanged without moving away focus. I thought setting UpdateSourceTrigger to PropertyChanged would do the trick but it didn't
VR Karthikeyan 31-Dec-15 3:12am    
Have you implemented INotifyPropertyChanged interface in your viemodel?
Lyandor 31-Dec-15 3:41am    
yes, the viewmodel looks like this:

private string inputString;
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string name)
{
PropertyChangedEventHandler hndl = this.PropertyChanged;

if (hndl !=null)
{
var e = new PropertyChangedEventArgs(name);
hndl(this,e);
}
}

public string InputString
{
get { return inputString;}
set
{
inputString = value;
OnPropertyChanged("InputString");
}
}
In TextBox Binding, set UpdateSourceTrigger to PropertyChanged. The code becomes like this:

XML
<textbox text="{Binding InputText, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource TemplatedParent}}" minwidth="150" />
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900