문제

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:

  • OwneType and DP type parameters are swapped in your registration.
  • DP wrappers are missing.
  • And make DP to bind 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top