百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

WPF 实现描点导航(wps描点作图)

zhezhongyun 2025-06-09 07:23 1 浏览

WPF 实现描点导航

控件名:NavScrollPanel

作 者:WPFDevelopersOrg - 驚鏵

原文链接[1]:https://github.com/WPFDevelopersOrg/WPFDevelopers

码云链接[2]:https://gitee.com/WPFDevelopersOrg/WPFDevelopers

  • 框架支持.NET4 至 .NET8
  • Visual Studio 2022;

有一位开发者需要实现类似「左侧导航栏 + 右侧滚动内容」的控件,需要支持数据绑定、内容模板、同步滚动定位等功能。

1. 新增 NavScrollPanel.cs
  • 左侧导航栏ListBox:显示导航,支持点击定位;
  • 右侧滚动内容区 ScrollViewerStackPanel:展示对应内容模板,支持滚动自动选中导航项。
  • 通过 ItemsSource 绑定内容集合;
  • 自定义 ItemTemplate 显示内容;
  • 通过 TranslatePoint 方法,可以获取元素相对于容器的坐标位置,并确保该位置不受 Margin 的影响。通过调用 ScrollToVerticalOffset 来滚动右侧容器;
public classNavScrollPanel : Control
{
static NavScrollPanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NavScrollPanel),
new FrameworkPropertyMetadata(typeof(NavScrollPanel)));
}

public IEnumerable ItemsSource
{
get => (IEnumerable)GetValue(ItemsSourceProperty);
set => SetValue(ItemsSourceProperty, value);
}

publicstaticreadonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register(nameof(ItemsSource), typeof(IEnumerable), typeof(NavScrollPanel), new PropertyMetadata(, OnItemsSourceChanged));

public DataTemplate ItemTemplate
{
get => (DataTemplate)GetValue(ItemTemplateProperty);
set => SetValue(ItemTemplateProperty, value);
}

publicstaticreadonly DependencyProperty ItemTemplateProperty =
DependencyProperty.Register(nameof(ItemTemplate), typeof(DataTemplate), typeof(NavScrollPanel), new PropertyMetadata());

publicint SelectedIndex
{
get => (int)GetValue(SelectedIndexProperty);
set => SetValue(SelectedIndexProperty, value);
}

publicstaticreadonly DependencyProperty SelectedIndexProperty =
DependencyProperty.Register(nameof(SelectedIndex), typeof(int), typeof(NavScrollPanel), new PropertyMetadata(-1, OnSelectedIndexChanged));

private ListBox _navListBox;
private ScrollViewer _scrollViewer;
private StackPanel _contentPanel;

public override void OnApplyTemplate()
{
base.OnApplyTemplate();

_navListBox = GetTemplateChild("PART_ListBox") as ListBox;
_scrollViewer = GetTemplateChild("PART_ScrollViewer") as ScrollViewer;
_contentPanel = GetTemplateChild("PART_ContentPanel") as StackPanel;

if (_navListBox != )
{
_navListBox.DisplayMemberPath = "Title";
_navListBox.SelectionChanged -= NavListBox_SelectionChanged;
_navListBox.SelectionChanged += NavListBox_SelectionChanged;
}
if (_scrollViewer != )
{
_scrollViewer.ScrollChanged += ScrollViewer_ScrollChanged;
}
RenderContent();
}

private void NavListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedIndex = _navListBox.SelectedIndex;
}

private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
double currentOffset = _scrollViewer.VerticalOffset;
double viewportHeight = _scrollViewer.ViewportHeight;

for (int i = 0; i < _contentPanel.Children.Count; i++)
{
var element = _contentPanel.Children[i] as FrameworkElement;
if (element == ) continue;

Point relativePoint = element.TranslatePoint(new Point(0, 0), _contentPanel);

if (relativePoint.Y >= currentOffset && relativePoint.Y < currentOffset + viewportHeight)
{
_navListBox.SelectionChanged -= NavListBox_SelectionChanged;
SelectedIndex = i;
_navListBox.SelectionChanged += NavListBox_SelectionChanged;
break;
}
}
}


private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is NavScrollPanel control)
{
control.RenderContent();
}
}

private static void OnSelectedIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is NavScrollPanel control)
{
int index = (int)e.NewValue;

if (control._contentPanel != &&
index >= 0 && index < control._contentPanel.Children.Count)
{
var target = control._contentPanel.Children[index] as FrameworkElement;
if (target != )
{
var virtualPoint = target.TranslatePoint(new Point(0, 0), control._contentPanel);
control._scrollViewer.ScrollToVerticalOffset(virtualPoint.Y);
}
}
}
}

private void RenderContent()
{
if (_contentPanel == || ItemsSource == || ItemTemplate == )
return;
_contentPanel.Children.Clear();
foreach (var item in ItemsSource)
{
var content = new ContentControl
{
Content = item,
ContentTemplate = ItemTemplate,
Margin = new Thickness(10,50,10,50)
};
_contentPanel.Children.Add(content);
}
}
}
2. 新增 NavScrollPanel.Xaml
  • 控件模板通过 ListBoxScrollViewer 实现。
<Style TargetType="local:NavScrollPanel">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:NavScrollPanel">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListBox
x:Name="PART_ListBox"
ItemsSource="{TemplateBinding ItemsSource}"
SelectedIndex="{TemplateBinding SelectedIndex}" />

<ScrollViewer
x:Name="PART_ScrollViewer"
Grid.Column="1"
VerticalScrollBarVisibility="Auto">

<StackPanel x:Name="PART_ContentPanel" />
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

3. 使用示例
1. 定义数据结构
public class SectionItem {
public string Title { get; set; }
public object Content { get; set; }
}
2. 初始化数据并绑定
Sections = new ObservableCollection<SectionItem>
{
new SectionItem{ Title = "播放相关", Content = new PlaybackSettings()},
new SectionItem{ Title = "桌面歌词", Content = new DesktopLyrics()},
new SectionItem{ Title = "快捷键", Content = new ShortcutKeys()},
new SectionItem{ Title = "隐私设置", Content = new PrivacySettings()},
new SectionItem{ Title = "关于我们", Content = new About()},
};
DataContext = this;

3. 模板定义
<DataTemplate x:Key="SectionTemplate">
<StackPanel>
<TextBlock Text="{Binding Title}" FontSize="20" Margin="0,10"/>
<Border Background="#F0F0F0" Padding="20" CornerRadius="10">
<ContentPresenter Content="{Binding Content}" FontSize="14"/>
</Border>
</StackPanel>
</DataTemplate>

4. 使用控件
<local:NavScrollPanel
ItemTemplate="{StaticResource SectionTemplate}"
ItemsSource="{Binding Sections}" />


5. 新增NavScrollPanelExample.xaml
<wd:Window
x:Class="WpfNavPanel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfNavPanel"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wd="https://github.com/WPFDevelopersOrg/WPFDevelopers"
Title="NavScrollPanel - 锚点导航"
Width="800"
Height="450"
mc:Ignorable="d">

<wd:Window.Resources>
<DataTemplate x:Key="SectionTemplate">
<StackPanel>
<TextBlock
Margin="0,10"
FontSize="20"
Text="{Binding Title}" />

<Border
Padding="20"
Background="#F0F0F0"
CornerRadius="10">

<ContentPresenter Content="{Binding Content}" TextElement.FontSize="14" />
</Border>
</StackPanel>
</DataTemplate>
</wd:Window.Resources>
<Grid Margin="4">
<local:NavScrollPanel ItemTemplate="{StaticResource SectionTemplate}" ItemsSource="{Binding Sections}" />
</Grid>
</wd:Window>


GitHub 源码地址[3]

Gitee 源码地址[4]

参考资料
[1]

原文链接: https://github.com/WPFDevelopersOrg/WPFDevelopers

[2]

码云链接: https://gitee.com/WPFDevelopersOrg/WPFDevelopers

[3]

GitHub 源码地址: https://github.com/WPFDevelopersOrg/WPFDevelopers

[4]

Gitee 源码地址: https://gitee.com/WPFDevelopersOrg/WPFDevelopers

相关推荐

Renaming column names in Pandas

技术背景在数据处理过程中,经常需要对数据框(DataFrame)的列名进行重命名,以满足数据分析、可视化或其他处理的需求。Pandas是Python中用于数据处理和分析的强大库,提供了多种重命名...

JSA宏教程WPS表格常用内置对象——应用程序(Application)对象

一、关于应用程序Application对象Application对象就是一个运行着的WPS表格(即ET)应用程序,它是整个应用程序根对象,在它之上没有其他程序对象了。ET在WPS的文件夹中的图标如下:...

Pandas通过columns属性访问、修改和删除列

在pandas中,DataFrame的列可以使用columns属性进行访问、修改或删除。以下是使用columns属性访问DataFrame列的示例代码:importpandasa...

excel的高级用法——宏,原来如此实用

使用excel时,直接手动计算或者输入公式,你会感到很苦恼或者操作很繁琐,如果使用vba直接输出结果,虽然效率很高,但是不够直观。excel宏最方便的用法是作为公式里的函数使用,打开宏编辑器,编写一个...

CSS grid-template-columns属性探讨|给你代码

CSSgrid布局CSSgrid布局是一种很强大的布局,兼容性如上表所示,表现在控制台里,你可以清楚看到他的内部每一个块都由一个虚线方块组成。他的每行每列都会生产一个单元格,而划分他们之间的线称为网...

7K star!Text2SQL还不够?试试RAG2SQL的开源工具

查询数据库离不开SQL,那如何快速构建符合自己期望的SQL呢?AI发展带来了Text2SQL的能力,众多产品纷纷提供了很好的支持。今天我们分享一个开源项目,它在Text2SQL的基础上还要继续提高,通...

用Python把表格做成web可视化图表

Python中有一个streamlit库,Streamlit的美妙之处在于您可以直接在Python中创建Web应用程序,而无需了解HTML、CSS或JavaScrip,今天我们就用st...

鸿蒙开发:使用Circle绘制圆形(鸿蒙圆角)

前言本文基于Api13上篇文章,我们使用Rect组件实现了矩形效果,本篇文章,我们继续探究几何图形的中圆形,实现矩形有多种形式,同样,圆形,也是有多种形式,在上篇的文章中也简单的做了几个案例,比如,我...

pandas读取Excel数据(.xlsx和.xls)

Python,速成心法敲代码,查资料,问Ai练习,探索,总结,优化★★★★★★★★★★Python教程:PyCharm安装过程中遇到的中英...

WPF - 4.布局(wpf 表单布局)

摘要WPF布局原则一个窗口中只能包含一个元素屏幕适应程序,不要显示设置的元素(控件)的尺寸,可以设置最小或者最大尺寸不应使用坐标设置元素的位置可以嵌套布局容器正文Grid面板通过Grid.RowDef...

前端开发避坑指南:每天都能用的 CSS3/Less/Sass 实战技巧

在前端开发这条路上,CSS3、Less和Sass就像三个形影不离的好兄弟。它们既能帮你打造出惊艳的页面效果,也会偶尔给你“挖坑”。今天就分享几个我在项目里摸爬滚打总结出的实战技巧,全是干货,拿...

WPF 实现描点导航(wps描点作图)

WPF实现描点导航控件名:NavScrollPanel作者:WPFDevelopersOrg-驚鏵原文链接[1]:https://github.com/WPFDevelopersOrg/WPF...

WPS表格自动绘制像素风格营销宣传海报文档

先看效果原图WPS表格(类Excel)效果,这不是贴图哦操作流程分解图片为BGR数值的二维数组化的CSV将二维数组的CSV导入数据,数据-导入-选择数据源-分隔符号-逗号-完成插入脚本,开发工具-WP...

Python读写docx文件(python读文档)

Python读写docx文件Python读写word文档有现成的库可以处理pipinstallpython-docx安装一下。https://python-docx.readthedocs.io/...

UWP开发入门(十七)--判断设备类型及响应VirtualKey

蜀黍我做的工作跟IM软件有关,UWP同时会跑在电脑和手机上。电脑和手机的使用习惯不尽一致,通常我倾向于根据窗口尺寸来进行布局的变化,但是特定的操作习惯是依赖于设备类型,而不是屏幕尺寸的,比如聊天窗口的...