简体   繁体   English

C#如何动态更改对象属性

[英]C# how to change object attributes dynamically

am reading this tutorial http://chalaki.com/how-to-program-msagl-glee-to-create-hierarchical-graph-layouts/519/ 正在阅读本教程http://chalaki.com/how-to-program-msagl-glee-to-create-hierarchical-graph-layouts/519/

using the code sample. 使用代码示例。

在此处输入图片说明

am trying to make the attributes dynamic (i want to be able to load the attributes from a database later) 正在尝试使属性动态化(我希望以后能够从数据库加载属性)

i have tried 我努力了

string dColor = "Red"; 
string dShape = "Diamond";

Microsoft.Glee.Drawing.Node n2 = graph.FindNode(strNode2);
n2.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.dColor;
n2.Attr.Shape = Microsoft.Glee.Drawing.Shape.dShape;

but its not working, how do i do this or even read about doing this dynamically? 但是它不起作用,我该怎么做,甚至阅读有关动态执行此操作的信息?

[ANSWER] Am not sure if this is the best way,but it works. [答案]不确定这是否是最好的方法,但是它可以工作。

--For Colors i did -对于我所做的色彩

using mColor = Microsoft.Msagl.Drawing.Color;
using sColor = System.Drawing.Color;

sColor c = sColor.FromName("Red");
graph.FindNode("test1").Attr.FillColor = new mColor(c.A,c.R,c.G,c.B);

--For the shape i did -我做的形状

 graph.FindNode("test1").Attr.Shape = (Shape)
 (int)Enum.Parse(typeof(Shape),"Diamond");

where "test1","diamond" and "Red" values come from the database. 其中“ test1”,“ diamond”和“ Red”值来自数据库。

A Color is not a string . Color不是string

Microsoft.Glee.Drawing.Node n2 = graph.FindNode(strNode2);
var someColor = System.Drawing.Color.Red;
n2.Attr.Fillcolor = someColor;

If you will be storing the colors in the database, you can use one of the static methods on Color: 如果要将颜色存储在数据库中,则可以在Color上使用静态方法之一:

string dColor = "Red"; 
n2.Attr.Fillcolor = Color.FromName(dColor);

If you will not stick to the named colors, there is also Color.FromArgb(int); 如果您不坚持使用指定的颜色,则还有Color.FromArgb(int);

EDIT 编辑

Looks like they are using a different Color class from the one in System.Drawing here. 看起来他们正在使用与System.Drawing中的Color类不同的Color类。 I found an example on the MSDN forums: 我在MSDN论坛上找到了一个示例

string color = "Red";
var cvtColor = new ColorConverter();
var sysColor = cvtColor.ConvertFromString(color);
n2.Attr.Fillcolor = new Microsoft.Msagl.Drawing.Color(sysColor.R, sysColor.B, sysColor.G);

There is some example code on GitHub : GitHub上有一些示例代码

n2.Attr.Fillcolor = Microsoft.Msagl.Drawing.Color.Magenta;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM