简体   繁体   English

为文本块创建事件

[英]Creating an Event for Textblock

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, 我正在尝试使用WindowsstoreApp(WPF)中的自定义依赖项属性为TextBlock创建TextChanged事件处理程序,该事件没有被触发,我不知道我哪里出了错,请指导我,到目前为止我一直在尝试,

 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 . 您的DP注册不正确 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. OwneType和DP类型参数在您的注册中交换。
  • DP wrappers are missing. DP包装器丢失。
  • And make DP to bind TwoWay . 并使DP绑定TwoWay Default is OneWay . 默认值为OneWay

Binding also is not correct. 绑定也不正确。 In case you want to bind to TextBlock name MyTextBlock, it should be: 如果要绑定到TextBlock名称MyTextBlock,则应为:

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. 我在WindowsStoreApp中找不到FrameworkPropertyMetadata。

In case FrameworkPropertyMetadata is not available on WinRT, use your PropertyMetadata , that will work as well. 如果WinRT上没有FrameworkPropertyMetadata ,请使用您的PropertyMetadata ,它也会正常工作。 But you need to set Mode to TwoWay on your binding. 但是您需要在绑定上将Mode设置为TwoWay I have updated the binding above. 我已经更新了上面的绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM