gpt4 book ai didi

c# - 使用 MVVM 的 TreeView BringIntoView

转载 作者:太空狗 更新时间:2023-10-29 20:01:27 25 4
gpt4 key购买 nike

我希望用户能够在 TreeView 中搜索项目。输入搜索文本后,TreeViewItem 应滚动到 View 中。

现在我正在为 TreeView、TreeViewItems 和 MainView 使用 MVVM 模式。

我需要做什么才能使用 MVVM 获得 BringIntoView 的功能?有一些我可以绑定(bind)的属性(property)吗? (在 MFC 中有类似 FirstVisibileItem 的东西)

已看到具有行为的“解决方案”。真的有必要吗?

最佳答案

根据提到的代码项目文章,这里是代码示例,展示了如何设置行为以及如何在 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
}

然后在 XAML 中集成 TreeViewItemBehavior:

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

玩得开心:-)

关于c# - 使用 MVVM 的 TreeView BringIntoView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15586844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com