Reputation: 789
Another way of asking this would be to say:
"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?"
To be clear: I'm just trying to set the value of a dependency property in the code behind
Here is my code:
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);
}
}
}
When I build the app, it succeeds!
But when I debug, it throws an Argument Exception as shown here:
Why am I getting this error and/or how do I fix it?
Upvotes: 0
Views: 521
Reputation: 39007
Just add ".0" at the end of your value to tell the compiler it's supposed to be a double:
TextBlock1.SetValue(FontSizeProperty, 24.0);
You can also use the "d" suffix:
TextBlock1.SetValue(FontSizeProperty, 24d);
As much as possible, you should use the strongly-typed property instead of the dependency property. This way, you can use implicit casting whenever possible, and the type errors will be caught at compilation time:
TextBlock1.FontSize = 24;
Behind the scenes the property will update the dependency property. So you get the exact same features, but with type-safety.
Upvotes: 5