WPF为什么定义附加行为需要这些方法?

时间:2014-02-19 21:05:28

标签: wpf attachedbehaviors

这两种方法似乎无法在任何地方调用。他们是否需要使用附加行为,或者只是方便获取财产?

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

1 个答案:

答案 0 :(得分:2)

没有;它们不是必需的。

这些只是与C#代码中的属性交互的简便方法;如果你不需要,就没有必要写它们。