【问题标题】:How could I save new objects when form is closing?表单关闭时如何保存新对象?
【发布时间】:2014-04-02 23:42:41
【问题描述】:

我编写了一个代码,它会在单击时创建一个新按钮。但我想保存新的按钮设置(可能在文件中)、大小等。表单关闭后,它们应该被保存,我们应该能够在重新打开时再次看到它们。我该怎么做?

谢谢...

【问题讨论】:

  • 通过写代码...
  • @L.B 当然可以,但是我应该写哪些代码?
  • @user3366576 but which codes i should write C# 代码。我们可以继续此对话,直到您发布到目前为止您已尝试过的内容,并询问您的问题在哪一部分。 SO不是“为我写代码”站点
  • @user3366576 - 您的代码绝对重要。为了得到好的答案,有必要展示你的作品。

标签: c# winforms


【解决方案1】:

创建一个包裹按钮的类。 (WrappedButton)

所以它将按钮作为构造函数的参数。

将要保存的属性添加到此类。高度、宽度、文字、左、右等

在构造函数中,根据按钮上的字段设置类上的字段。

将所有 WrappedButtons 放入一个列表中。

使用以下代码在文件中保存和加载列表。

   public static void SaveListOfT_ToFile< T >( List< T > l, string filename )
   {
      Type[] extraTypes = new Type[1];
      extraTypes[ 0 ] = typeof ( T );

      XmlSerializer xs = new XmlSerializer( typeof ( List< T > ), extraTypes );

      using ( StreamWriter writer = new StreamWriter( filename ) )
      {
         xs.Serialize( writer, l );
      }
   }

   public static List< T > LoadListOfT_FromFile< T >( string filename )
   {
      try
      {
         Type[] extraTypes = new Type[1];
         extraTypes[ 0 ] = typeof ( T );

         XmlSerializer xs = new XmlSerializer( typeof ( List< T > ), extraTypes );
         List< T > a;

         using ( FileStream f = new FileStream( filename, FileMode.Open ) )
         {
            // Use the Deserialize method to restore the object's state with
            // data from the XML document. 
            a = ( List< T > )xs.Deserialize( f );
         }


         return a;
      }
      catch ( Exception )
      {
         return null;
      }
   }

【讨论】:

    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2023-03-16
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多