【发布时间】:2020-03-01 06:36:38
【问题描述】:
我正在开发一个 WPF 应用程序,并且我正在尝试在不参考 Windows 窗体的情况下执行此操作。我实际上使用的是Wpf Font Picker by Alessio Saltarin,它是一个字体选择器,带有完全在 WPF 中开发的颜色选择器。
我想要做的是让用户选择一种字体+颜色并保存他们的选择,以便恢复它以重新启动应用程序。字体存储在 FontInfo 类中:
public class FontInfo
{
public SolidColorBrush BrushColor { get; set; }
public FontColor Color { get { return AvailableColors.GetFontColor(this.BrushColor); } }
public FontFamily Family { get; set; }
public double Size { get; set; }
public FontStretch Stretch { get; set; }
public FontStyle Style { get; set; }
public FontWeight Weight { get; set; }
public FamilyTypeface Typeface
{
get
{
FamilyTypeface ftf = new FamilyTypeface()
{
Stretch = this.Stretch,
Weight = this.Weight,
Style = this.Style
};
return ftf;
}
}
public FontInfo() { }
public FontInfo(FontFamily fam, double sz, FontStyle style, FontStretch strc, FontWeight weight, SolidColorBrush c)
{
this.Family = fam;
this.Size = sz;
this.Style = style;
this.Stretch = strc;
this.Weight = weight;
this.BrushColor = c;
}
public static void ApplyFont(Control control, FontInfo font)
{
control.FontFamily = font.Family;
control.FontSize = font.Size;
control.FontStyle = font.Style;
control.FontStretch = font.Stretch;
control.FontWeight = font.Weight;
control.Foreground = font.BrushColor;
}
public static FontInfo GetControlFont(Control control)
{
FontInfo font = new FontInfo()
{
Family = control.FontFamily,
Size = control.FontSize,
Style = control.FontStyle,
Stretch = control.FontStretch,
Weight = control.FontWeight,
BrushColor = (SolidColorBrush)control.Foreground
};
return font;
}
public static string TypefaceToString(FamilyTypeface ttf)
{
StringBuilder sb = new StringBuilder(ttf.Stretch.ToString());
sb.Append("-");
sb.Append(ttf.Weight.ToString());
sb.Append("-");
sb.Append(ttf.Style.ToString());
return sb.ToString();
}
}
我没有明白什么是最佳选择。我看到它可以通过 XML 序列化来实现,但我失败了,我看到每个示例都使用带有字符串和 int 变量的简单类。
请给我一些文档或者给我一个例子来说明如何做到这一点?
【问题讨论】:
-
@BionicCode 非常感谢您的回答。我正在阅读这些文件,但我遇到了与 Tronald 回答相同的问题。如果我尝试序列化我的类,我会收到一个错误,因为我无法序列化其中的对象。
-
我添加了一个答案来展示如何通过实现
ISerializable来解决这个问题。
标签: c# wpf class save settings