9

ユーザーがTreeViewでアイテムを検索できるようにしたいと思います。検索テキストを入力した後、TreeViewItemをスクロールして表示する必要があります。

現在、TreeView、TreeViewItems、およびMainViewにMVVMパターンを使用しています。

MVVMを利用してBringIntoViewの機能を取得するにはどうすればよいですか?バインドできるプロパティはありますか?(MFCにはFirstVisibileItemのようなものがありました)

行動を伴う「解決策」を見たことがあります。本当に必要ですか?

4

2 に答える 2

11

前述のCodeProjectの記事によると、Behaviorをセットアップする方法とBehaviorをXAMLに統合する方法を示すコード例を次に示します。

動作を設定します。

/// <summary>
/// Exposes attached behaviors that can be
/// applied to TreeViewItem objects.
/// </summary>
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
}

次に、TreeViewItemBehaviorをXAMLに統合します。

<TreeView.ItemContainerStyle>
  <Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="local:TreeViewItemBehavior.IsBroughtIntoViewWhenSelected" Value="True"/>
  </Style>
</TreeView.ItemContainerStyle>

楽しむ :-)

于 2015-03-04T10:27:12.980 に答える
4

この問題はビヘイビアで解決できます。

このCodeProjectの記事では、非常に優れていると説明しており、すぐに使用できます。

于 2013-03-23T19:05:13.590 に答える