Dependency 属性 的 SetValue 需要一个对象:如何设置 FontSize属性?

SetValue for Dependency Property requires an object: How do I set the FontSizeProperty?

另一种提问方式是:

"How do I set the value of an object to 24 so I can pass it as an argument to the SetValue()'s value parameter?"

明确一点:我只是想在后面的代码中设置依赖项 属性 的值

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Foo {

  public partial class MainWindow : Window {
    public MainWindow() {
      InitializeComponent();

      TextBlock1.Text = "bar";

      TextBlock1.SetValue(FontSizeProperty, 24);
    }
  }
}

当我构建 应用程序时,它成功了!

但是当我调试时,它会抛出一个参数异常,如下所示:

为什么我会收到此错误and/or我该如何解决?

FontSize expects a double.

只需在值的末尾添加“.0”即可告诉编译器它应该是双精度数:

TextBlock1.SetValue(FontSizeProperty, 24.0);

您还可以使用 "d" 后缀:

TextBlock1.SetValue(FontSizeProperty, 24d);

您应该尽可能使用强类型 属性 而不是依赖 属性。这样,您可以尽可能使用隐式转换,类型错误将在编译时被捕获:

TextBlock1.FontSize = 24;

在幕后 属性 将更新依赖项 属性。因此,您可以获得完全相同的功能,但具有类型安全性。