2014-11-14 91 views
0

我想翻譯這個代碼志願在C#

[self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionPrior context:NULL]; 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{ 
    if ([keyPath isEqualToString:@"contentSize"]) { 
     DLog(@"change = %@", change.description) 

     NSValue *new = [change valueForKey:@"new"]; 
     NSValue *old = [change valueForKey:@"old"]; 

     if (new && old) { 
      if (![old isEqualToValue:new]) { 
       // do your stuff 
      } 
     } 
    } 
} 

到C#。 (從Get notified when UITableView has finished asking for data?拍攝)

這我怎麼走到這一步:

this.TableView.AddObserver ("contentSize", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.Prior, null); 

public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) 
{ 
    //base.ObserveValue (keyPath, ofObject, change, context); 

    if (keyPath == "contentSize") { 
     NSValue newValue = (NSValue)NSValue.FromObject(change["new"]); 
     NSValue oldValue = (NSValue)NSValue.FromObject(change["old"]); 

     //if (newValue && oldValue) { 
      if(!oldValue.IsEqualTo(newValue)){ 
       // do something here 
      } 
     //} 
    } 
} 

我的問題是:

  1. 如何轉換的NSObject至NSValue?
  2. 如何檢查NSValue是否有有效值?
  3. 我該如何處理Action<NSObservedChange> observer
  4. 我如何得到這個工作?

回答

1
void AddObservers() 
    { 
     TextView.AddObserver(this, "contentSize", NSKeyValueObservingOptions.OldNew, IntPtr.Zero); 
    } 

    public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) 
    { 
     if (keyPath == "contentSize") 
      OnSizeChanged(new NSObservedChange(change)); 
     else 
      base.ObserveValue(keyPath, ofObject, change, context); 
    } 

    void OnSizeChanged(NSObservedChange change) 
    { 
     CGSize oldValue = ((NSValue)change.OldValue).CGSizeValue; 
     CGSize newValue = ((NSValue)change.NewValue).CGSizeValue; 

     var dy = newValue.Height - oldValue.Height; 
    } 

看這個monotouch-samples.