2014-02-13 32 views
0

我想創建TextBlock的TextChanged事件處理程序使用WindowsstoreApp(WPF)中的自定義依賴屬性,事件沒有被解僱,我不知道我錯了哪裏,請指導我,我已經嘗試到目前爲止,爲文本塊創建事件

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

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。

如果FrameworkPropertyMetadata不適用於WinRT的,用你的PropertyMetadata,將正常工作。但是您需要在綁定上將Mode設置爲TwoWay。我已經更新了上面的綁定。

+0

感謝您的答案,但我無法在WindowsStoreApp中找到FrameworkPropertyMetadata。 – DesertRiver

+0

哦,所以用你的PropertyChangeCallback和其他改變。那可行。您必須在綁定時設置「Mode = TwoWay」。 –

+0

您能否詳細解釋一下PropertyChangeCallback? – DesertRiver