2014-02-19 30 views
0

這兩個方法似乎沒有被調用到任何地方。他們是否需要使用附加的行爲,或者他們只是獲得財產的便利?WPF爲什麼在定義附加行爲時需要這些方法?

public static bool GetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem) 
{ 
    return (bool)treeViewItem.GetValue(IsBroughtIntoViewWhenSelectedProperty); 
} 

public static void SetIsBroughtIntoViewWhenSelected(
    TreeViewItem treeViewItem, bool value) 
{ 
    treeViewItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value); 
} 

全部從實施例的代碼在http://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF

public static class TreeViewItemBehavior 
{ 
    #region IsBroughtIntoViewWhenSelected 

    public static bool GetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem) 
    { 
     return (bool)treeViewItem.GetValue(IsBroughtIntoViewWhenSelectedProperty); 
    } 

    public static void SetIsBroughtIntoViewWhenSelected(
     TreeViewItem treeViewItem, bool value) 
    { 
     treeViewItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value); 
    } 

    public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty = 
     DependencyProperty.RegisterAttached(
     "IsBroughtIntoViewWhenSelected", 
     typeof(bool), 
     typeof(TreeViewItemBehavior), 
     new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged)); 

    static void OnIsBroughtIntoViewWhenSelectedChanged(
     DependencyObject depObj, DependencyPropertyChangedEventArgs e) 
    { 
     TreeViewItem item = depObj as TreeViewItem; 
     if (item == null) 
      return; 

     if (e.NewValue is bool == false) 
      return; 

     if ((bool)e.NewValue) 
      item.Selected += OnTreeViewItemSelected; 
     else 
      item.Selected -= OnTreeViewItemSelected; 
    } 

    static void OnTreeViewItemSelected(object sender, RoutedEventArgs e) 
    { 
     // Only react to the Selected event raised by the TreeViewItem 
     // whose IsSelected property was modified. Ignore all ancestors 
     // who are merely reporting that a descendant's Selected fired. 
     if (!Object.ReferenceEquals(sender, e.OriginalSource)) 
      return; 

     TreeViewItem item = e.OriginalSource as TreeViewItem; 
     if (item != null) 
      item.BringIntoView(); 
    } 

    #endregion // IsBroughtIntoViewWhenSelected 
+2

否;他們不是必需的。 – SLaks

+0

SLaks +1。 IsBroughtIntoViewWhenSelected可能設置在xaml的某處。這兩個獲取和設置方法並非真正需要的。如果您想要手動讀取或設置代碼值,它們只是助手。 –

+0

@SLaks,你可以在回答中稍微擴展一下你的評論,以便這個問題可以被標記爲接受嗎? – Sheridan

回答

2

否;他們不是必需的。

這些只是與C#代碼中的屬性進行交互的簡便方法;如果你不需要,就不需要編寫它們。

相關問題