保存控件,然后重新加载它们 [英] Saving controls then reloading them

查看:101
本文介绍了保存控件,然后重新加载它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我是wpf和C#的新手.我想在运行时创建一个按钮,更改它的名称,然后在我关闭应用程序时应保存它,而当我重新加载该应用程序时,该按钮应该在那儿.

在运行时创建按钮很容易,但是找到将按钮创建的最佳方法保存在可移植的位置(如果重新安装应用程序则可重复使用)并不是最好的方法.我已经读过有关my.Settings,Xaml编写器,隔离存储,使用数据库,注册表等内容的信息,说实话我迷路了.

哪个是最佳解决方案以及如何实施?

谢谢.

MAK

Hi,

I am new to wpf and C#. I would like to create a button at runtime,change its name then when I close the application it should be saved and when I reload the application the button should be there.

Creating the button at run time is easy but finding the best way to save the button created somewhere that can be portable(reusable if the application is reinstalled) isn''t. I''ve read about my.Settings,Xaml writer,Isolated storage, using databases, the registry and so on and honestly I am lost.

Which is the best solution and how to implement it?

Thank you.

MAK

推荐答案

我将与您要保存的内容(在这种情况下为某些对象的名称)和UI(即XAML,您已经可以使用该按钮了.将模型信息(对象名称,事物列表等,在不知道软件是什么的情况下很难在此处指定)保存在您喜欢的任何存储工具(纯文本文件,XML文件,数据库,更合适的文件)中.

然后,在加载应用程序时,按正常方式构建UI,然后根据您已加载回的模型信息对其进行更新.
I would separate the information that''s actually relevant to what you want to save (in this case the name of some object) and the UI (the XAML you have already for that button). Save the model information (names of objects, lists of things and so on, hard to be specific here without knowing what the software is) in whatever storage facility you like (plain text file, XML file, database, whatever is more appropriate).

And then when you load the application, build the UI as normal and then update it based on the model information you''ve loaded back.


您有两种解决方案:
1.动态创建应用程序布局,然后从外部XAML加载它.添加按钮,覆盖XAML.可能是最简单的方法.
2.将有关您创建的新控件的一些信息(大小,位置,父级等)保存在某处.在运行时加载信息,搜索父项并添加新控件.可能由于WPF中的视觉/逻辑树而更加复杂.
You have two solutions:
1. Create application layout dynamically, loading it from an external XAML. Add the button, overwrite the XAML. Probably it''s the simplest way.
2. Save some information about the new controls (size, location, parent, etc..) you create somewhere. At runtime load the information, search for parents and add the new controls. Might be more complicated because of visual/logical tree(s) in WPF.


如果有用,下面是一些示例代码,这些代码将Runs添加到通过字符串动态创建的TextBlock中:
If useful, here is some example code that add Runs to a TextBlock dynamically created from a String:
Inlines.Clear();
Text = null;

if (value == null) return;
StringBuilder SB = new StringBuilder();

SB.Append("<TextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">");
SB.Append(value.ToString().Replace("\r\n", "<LineBreak/>"));
SB.Append("</TextBlock>");

var TB =
  XamlReader.Load(new System.Xml.XmlTextReader(
    new System.IO.StringReader(SB.ToString()))) as TextBlock;
var Lista = TB.Inlines.ToArray();

foreach (var item in Lista)
{
  this.Inlines.Add(item);
}


这篇关于保存控件,然后重新加载它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆