C#属性显示

功能:
显示对象的属性,包括可显示属性、可编辑属性、及不可编辑属性。
1、MainWindow.xaml

<Window x:Class="FlowChart.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:FlowChart"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><DockPanel><StackPanel DockPanel.Dock="Left" Width="300" Margin="0 0 10 0"><StackPanel Margin="0 10 0 10"><TextBlock Text="属性" FontWeight="Bold" Margin="0 0 0 10"/><local:PropertiesView x:Name="_propertiesView" Height="200"/></StackPanel></StackPanel><Border BorderBrush="Black" BorderThickness="1"></Border></DockPanel>
</Window>

2、MainWindow.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace FlowChart
{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();DataInitialize();}public List<Selection> selections=new List<Selection>();public void DataInitialize(){Selection selection = new Selection();selection.Location=new Point(0,0);selection.Size=new Size(200,200);//selection.Name = "测试";_propertiesView.SelectedObject= selection;}}public class Selection:INotifyPropertyChanged{private Point _location;public Point Location{get { return _location; }set{_location = value;OnPropertyChanged("Location");}}private Size _size;//[Browsable(false)]public Size Size{get { return _size; }set{_size = value;OnPropertyChanged("Size");}}private string _name="Test";public string Name{get { return _name; }//set { _name = value;//    OnPropertyChanged("Name");//}}public override string ToString(){return GetType().Name;}public event PropertyChangedEventHandler PropertyChanged;protected void OnPropertyChanged(string name){if (PropertyChanged != null)PropertyChanged(this, new PropertyChangedEventArgs(name));}}
}

3、PropertiesView.xaml

<UserControl x:Class="FlowChart.PropertiesView"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:FlowChart"mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="300"><UserControl.Resources><ControlTemplate x:Key="validationErrorTemplate"><DockPanel><Image Source="Resources\empty.png" Height="16" Width="16" DockPanel.Dock="Right" Margin="-18 0 0 0"ToolTip="{Binding ElementName=adorner,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"></Image><AdornedElementPlaceholder x:Name="adorner"/></DockPanel></ControlTemplate><Style x:Key="gridLineStyle" TargetType="Line"><Setter Property="Stroke" Value="Gray" /><Setter Property="Stretch" Value="Fill" /><Setter Property="Grid.ZIndex" Value="1000" /></Style><Style x:Key="gridHorizontalLineStyle" TargetType="Line" BasedOn="{StaticResource gridLineStyle}"><Setter Property="X2" Value="1" /><Setter Property="VerticalAlignment" Value="Bottom" /><Setter Property="Grid.ColumnSpan"Value="{Binding Path=ColumnDefinitions.Count,RelativeSource={RelativeSource AncestorType=Grid}}"/></Style><Style x:Key="gridVerticalLineStyle" TargetType="Line" BasedOn="{StaticResource gridLineStyle}"><Setter Property="Y2" Value="1" /><Setter Property="HorizontalAlignment" Value="Right" /><Setter Property="Grid.RowSpan" Value="{Binding Path=RowDefinitions.Count,RelativeSource={RelativeSource AncestorType=Grid}}"/></Style></UserControl.Resources><Border BorderThickness="1" BorderBrush="Black"><DockPanel x:Name="_panel"><Border x:Name="_label" Width="50" Height="16"><TextBlock Text="Empty" TextAlignment="Center" Foreground="Gray"/></Border><ScrollViewer x:Name="_gridContainer" VerticalScrollBarVisibility="Auto"><Grid x:Name="_grid"><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><Line Name="_vLine" Grid.Column="0" Grid.RowSpan="1000" Style="{StaticResource gridVerticalLineStyle}"/><GridSplitter Name="_splitter" Grid.RowSpan="1000"  Margin="0,0,-2,0" Width="4" Background="White" Opacity="0.01" Grid.ZIndex="10000"/></Grid></ScrollViewer></DockPanel></Border>
</UserControl>

4、PropertiesView.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace FlowChart
{/// <summary>/// PropertiesView.xaml 的交互逻辑/// </summary>public partial class PropertiesView : UserControl{public PropertiesView(){InitializeComponent();DisplayProperties();}private object _selectedObject;public object SelectedObject{get { return _selectedObject; }set{if (_selectedObject != value){var obj = _selectedObject as INotifyPropertyChanged;if (obj != null)obj.PropertyChanged -= PropertyChanged;_selectedObject = value;DisplayProperties();obj = _selectedObject as INotifyPropertyChanged;if (obj != null)obj.PropertyChanged += PropertyChanged;}}}void PropertyChanged(object sender, PropertyChangedEventArgs e){DisplayProperties();}private void DisplayProperties(){_panel.Children.Clear();ClearGrid();if (SelectedObject != null){int row = 0;foreach (var prop in SelectedObject.GetType().GetProperties().OrderBy(p => p.Name)){var attr = prop.GetCustomAttributes(typeof(BrowsableAttribute), true);if (attr.Length == 0 || (attr[0] as BrowsableAttribute).Browsable){DisplayProperty(prop, row);row++;}}_panel.Children.Add(_gridContainer);}else{_panel.Children.Add(_label);}}private void ClearGrid(){_grid.RowDefinitions.Clear();for (int i = _grid.Children.Count - 1; i >= 0; i--){if (_grid.Children[i] != _vLine && _grid.Children[i] != _splitter)_grid.Children.RemoveAt(i);}}private void DisplayProperty(PropertyInfo prop, int row){var rowDef = new RowDefinition();rowDef.Height = new GridLength(Math.Max(20, this.FontSize * 2));_grid.RowDefinitions.Add(rowDef);var tb = new TextBlock() { Text = prop.Name };tb.Margin = new Thickness(4);Grid.SetColumn(tb, 0);Grid.SetRow(tb, _grid.RowDefinitions.Count - 1);var ed = new TextBox();ed.PreviewKeyDown += new KeyEventHandler(ed_KeyDown);ed.Margin = new Thickness(0, 2, 14, 0);ed.BorderThickness = new Thickness(0);Grid.SetColumn(ed, 1);Grid.SetRow(ed, _grid.RowDefinitions.Count - 1);var line = new Line();line.Style = (Style)Resources["gridHorizontalLineStyle"];Grid.SetRow(line, row);var binding = new Binding(prop.Name);binding.Source = SelectedObject;binding.ValidatesOnExceptions = true;binding.Mode = BindingMode.OneWay;ed.IsEnabled = false;if (prop.CanWrite){ed.IsEnabled = true;var mi = prop.GetSetMethod();if (mi != null && mi.IsPublic)binding.Mode = BindingMode.TwoWay;}ed.SetBinding(TextBox.TextProperty, binding);var template = (ControlTemplate)Resources["validationErrorTemplate"];Validation.SetErrorTemplate(ed, template);_grid.Children.Add(tb);_grid.Children.Add(ed);_grid.Children.Add(line);}void ed_KeyDown(object sender, KeyEventArgs e){var ed = sender as TextBox;if (ed != null){if (e.Key == Key.Enter){ed.GetBindingExpression(TextBox.TextProperty).UpdateSource();e.Handled = true;}else if (e.Key == Key.Escape)ed.GetBindingExpression(TextBox.TextProperty).UpdateTarget();}}}
}

5、运行结果
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/577121.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity颗粒血条的实现(原创,参考用)

1.创建3个静态物体摆好位置&#xff0c;并将其图层设为UI 2.编写一个脚本 using System.Collections; using System.Collections.Generic; using UnityEngine;public class xt : MonoBehaviour {public GameObject xt1;public GameObject xt2;public GameObject xt3;int x 1;…

住宅IP是什么?与机房IP有哪些区别?

随着互联网的普及和发展&#xff0c;不同类型的IP地址在网络世界中扮演着重要角色。在网络架构中&#xff0c;机房IP和住宅IP是两种常见的IP类型&#xff0c;它们各有优劣&#xff0c;适用于不同的场景和需求。本文将对机房IP和住宅IP进行技术对比&#xff0c;并给出选择合适IP…

Oracle存数字精度问题number、binary_double、binary_float类型

--表1 score是number(10,5)类型 create table TEST1 (score number(10,5) ); --表2 score是binary_double类型 create table TEST2 (score binary_double ); --表3 score是binary_float类型 create table TEST3 (score binary_float );实验一&#xff1a;分别往三张表插入 小数…

【C++杂货铺】内管管理

目录 &#x1f308;前言&#x1f308; &#x1f4c1; C/C中内存分布 &#x1f4c1; new 和 delete的使用 &#x1f4c1; new 和 delete的优点 &#x1f4c1; new 和 delete的原理 &#x1f4c2; operator new 和 operator delete函数 &#x1f4c2; 内置类型 &#x1f4c2…

小狐狸JSON-RPC:wallet_addEthereumChain(添加指定链)

wallet_addethereumchain&#xff08;添加网络&#xff09; var res await window.ethereum.request({"method": "wallet_addEthereumChain","params": [{"chainId": "0x64", // 链 ID &#xff08;必填&#xff09;"…

职场沟通教训 程序汪改了一行代码,导致测试和开发大战

本文章有视频的&#xff0c;请到B站 我是程序汪 观看 程序汪改了一行代码&#xff0c;导致测试和开发大战&#xff0c;职场沟通教训 程序汪改了一行代码&#xff0c;导致测试和开发大战 鸡汤文 每个人都会在沟通上出问题 工作上沟通出问题可能让你郁闷一天、丢了客户、损失金…

机器学习作业二之KNN算法

KNN&#xff08;K- Nearest Neighbor&#xff09;法即K最邻近法&#xff0c;最初由 Cover和Hart于1968年提出&#xff0c;是一个理论上比较成熟的方法&#xff0c;也是最简单的机器学习算法之一。该方法的思路非常简单直观&#xff1a;如果一个样本在特征空间中的K个最相似&…

每日一题 --- 快乐数[力扣][Go]

快乐数 题目&#xff1a;202. 快乐数 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」 定义为&#xff1a; 对于一个正整数&#xff0c;每一次将该数替换为它每个位置上的数字的平方和。然后重复这个过程直到这个数变为 1&#xff0c;也可能是 无限循环 但始终变不到…

GitLab更新失败(Ubuntu)

在Ubuntu下使用apt更新gitlab报错如下&#xff1a; An error occurred during the signature verification.The repository is not updated and the previous index files will be used.GPG error: ... Failed to fetch https://packages.gitlab.com/gitlab/gitlab-ee/ubuntu/d…

揭秘百度百科审核内幕,百科词条审核究竟需要多久?

百度百科作为国内最大的网络百科全书平台之一&#xff0c;致力于提供全面、准确的知识服务&#xff0c;同时也承担着审核百科词条的工作。在互联网时代&#xff0c;人们对信息的需求日益增长&#xff0c;因此百度百科的审核工作显得尤为重要。那么&#xff0c;百度百科词条审核…

Codigger用户篇:安全、稳定、高效的运行环境(二)

在当今数字化时代&#xff0c;随着云计算和大数据技术的飞速发展&#xff0c;分布式操作系统已成为支撑各类应用高效运行的关键基础设施。我们推出的Codigger分布式操作系统&#xff0c;正是为了满足用户对安全、稳定、高效私人应用运行环境的需求而精心设计的。上一次&#xf…

【大数据运维】minio 常见shell操作

文章目录 1. 安装2. 入门操作3. 命令帮助 1. 安装 下载 https://dl.min.io/client/mc/release/linux-amd64/ 赋权与使用 cp mc /usr/bin && chmod x /usr/bin/mc ./mc --help 2. 入门操作 # 添加minio到mc mc config host add minio_alias_name endpoint_adress …