I am trying to create a TextChanged Event Handler for a TextBlock using Custom Dependency Property in WindowsstoreApp(WPF),The Event is not getting fired,I dont know where I went wrong,Please guide me ,I have tried so far is,
public sealed partial class BuyerInput : Page
{
public BuyerInput()
{
this.InitializeComponent();
MyTextblock.SetBinding(MyTextProperty, new Binding { Source = MyTextblock.Text,Path = new PropertyPath("MyText") });
}
public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText", typeof(BuyerInput), typeof(string), new PropertyMetadata(null, OnMyTextChanged));
public static void OnMyTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//this event is not getting fired whenever the value is changed in TextBlock(MyTextblock)
}
}
Your DP registration is incorrect. It should be like this:
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register("MyText", typeof(string), typeof(BuyerInput),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
PropertyChangedCallback = OnMyTextChanged
});
public string MyText
{
get { return (string)GetValue(MyTextProperty); }
set { SetValue(MyTextProperty, value); }
}
private static void OnMyTextChanged(DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
}
Explanation:
TwoWay
. Default is OneWay
.Binding also is not correct. In case you want to bind to TextBlock name MyTextBlock, it should be:
MyTextblock.SetBinding(TextBlock.TextProperty,
new Binding { Source = this,Path = new PropertyPath("MyText"),
Mode=BindingMode.TwoWay });
Update for comment -
I can't find FrameworkPropertyMetadata in WindowsStoreApp.
In case FrameworkPropertyMetadata
is not available on WinRT, use your PropertyMetadata
, that will work as well. But you need to set Mode
to TwoWay
on your binding. I have updated the binding above.