为Textblock创建事件

时间:2014-02-13 06:18:30

标签: c# wpf data-binding windows-store-apps textblock

我正在尝试使用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)
    }
}

1 个答案:

答案 0 :(得分:1)

您的 DP注册不正确。它应该是这样的:

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)
{
}

<强>解释

  • OwneType和DP类型参数在您的注册中交换。
  • 缺少DP包装。
  • 并使DP绑定TwoWay。默认值为OneWay

绑定也不正确。如果你想绑定到TextBlock名称MyTextBlock,它应该是:

MyTextblock.SetBinding(TextBlock.TextProperty,
      new Binding { Source = this,Path = new PropertyPath("MyText"), 
                    Mode=BindingMode.TwoWay });

更新以发表评论 -

  

我在WindowsStoreApp中找不到FrameworkPropertyMetadata。

如果WinRT上没有FrameworkPropertyMetadata,请使用您的PropertyMetadata,这也会有效。但是您需要在绑定上将Mode设置为TwoWay。我已经更新了上面的绑定。

相关问题