简体   繁体   中英

Why does: '18 is not a valid value for the property "System.Windows.Documents.TextElement.FontSize" on a setter.' get thrown when setting FontSize?

I want to create a "DataGrid" in "WPF" when a "Button" is pressed.

Everything went fine, until I wanted to change the "FontSize" of the "ColumnHeader".

My Code so far:

var list = new ObservableCollection<TestClassForDataGrid>
        {
            new() { id = 1, name = "Herbert", bday = DateTime.Now },
            new() { id = 2, name = "Harald", bday = DateTime.Now }
        };
        var fontSizeSetter = new Setter(Control.FontSizeProperty, 18);
        var columnHeaderStyle = new Style(typeof(DataGridColumnHeader))
        {
            Setters = { fontSizeSetter }
        };
        var dataGrid = new DataGrid
        {
            ItemsSource = list,
            AutoGenerateColumns = false,
            ColumnHeaderStyle = columnHeaderStyle
        };
        dataGrid.Columns.Add(new DataGridTextColumn()
            { Binding = new Binding(path: "id"), Header = "ID", FontSize = 18 });
        dataGrid.Columns.Add(new DataGridTextColumn()
            { Binding = new Binding(path: "name"), Header = "Name", FontSize = 18 });
        dataGrid.Columns.Add(new DataGridTextColumn()
            { Binding = new Binding(path: "bday"), Header = "Birthday", FontSize = 18 });
        Grid.SetColumn(dataGrid, 1);
        Grid.SetRow(dataGrid, 1);
        Grid.SetColumnSpan(dataGrid, 3);
        Grid.SetRowSpan(dataGrid, int.MaxValue);
        GridContent.Children.Add(dataGrid);

That is the Code inside my "OnClick" method.

Whenever I try to call this Method, I get an "Exception" saying, the Value 18 is not a valid property for "FontSize".

I also tried to set it as a string, but that gave mt the same error.

The "FontSize" in the "DataGridTextcolumn" works fine.

Why do I get this error?

I found the solution to this exception and it was a quite simple solution.

"FontSize" takes a double as it's parameter and C# sees 18 as an "int32".

For unknown reasons is it not possible for the constructor of the "Setter" class to implicitly convert the integer to double and throws this exception.

Just adding ".0" is enough to fix everything.

var fontSizeSetter = new Setter(Control.FontSizeProperty, 18.0);

The "Setter" class seems to be very picky with the datatype it gets and if it is not correct it freaks out.

Hopefully this will help someone in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM