如何使用WPF打开颜色和字体对话框?

Ben*_*man 4 wpf dialog

我想在WPF .net 4.5中显示颜色和字体对话框,我该怎么办?请帮助我任何人.

Thnx in Advanced!

Dav*_*_cz 8

最好的开箱即用解决方案是使用FontDialog表单System.Windows.Forms汇编,但您必须转换它的输出以将其应用于WPF元素.

FontDialog fd = new FontDialog();
var result = fd.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
    Debug.WriteLine(fd.Font);

    tbFonttest.FontFamily = new FontFamily(fd.Font.Name);
    tbFonttest.FontSize = fd.Font.Size * 96.0 / 72.0;
    tbFonttest.FontWeight = fd.Font.Bold ? FontWeights.Bold : FontWeights.Regular;
    tbFonttest.FontStyle = fd.Font.Italic ? FontStyles.Italic : FontStyles.Normal;

    TextDecorationCollection tdc = new TextDecorationCollection();
    if (fd.Font.Underline) tdc.Add(TextDecorations.Underline);
    if (fd.Font.Strikeout) tdc.Add(TextDecorations.Strikethrough);
    tbFonttest.TextDecorations = tdc;
}
Run Code Online (Sandbox Code Playgroud)

请注意,winforms对话框不支持许多WPF字体属性,如额外的粗体字体.

颜色对话框更容易:

ColorDialog cd = new ColorDialog();
var result = cd.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
    tbFonttest.Foreground = new SolidColorBrush(Color.FromArgb(cd.Color.A, cd.Color.R, cd.Color.G, cd.Color.B));
}
Run Code Online (Sandbox Code Playgroud)

它虽然不支持alpha.


Ath*_*ari 1

您可以使用 中的类System.Windows.Forms,使用它们没有任何问题。不过,您可能需要将值转换为 WPF 特定的值。

或者,您可以实现自己的对话框或使用第三方控件,请参阅WPF 的免费字体和颜色选择器?