简体   繁体   中英

Can't set TextBox.MinWidthProperty when creating a VisualTree for GridViewColumn.DataTemplate

I have am trying to set a GridViewColumn.DataTemplate to a TextBox VisualTree. The code so far is:

//GridViewColumnCollection columns
DataTemplate template = new DataTemplate();
FrameworkElementFactory elementFactory = new FrameworkElementFactory(typeof(TextBox));
elementFactory.SetBinding(TextBox.TextProperty, new Binding { Path = new PropertyPath("Position") });
elementFactory.SetValue(TextBox.MinWidthProperty, new GridLength(50));
template.VisualTree = elementFactory;
columns[1].CellTemplate = template;

When I run this code I get the following error:

50 is not a valid value for property 'MinWidth'.

on this line: elementFactory.SetValue(TextBox.MinWidthProperty, new GridLength(50));

I also tried setting the value to just 50, but to no avail!

在此输入图像描述

What am I doing wrong?

Thanks in advance.

According to MSDN , the MinWidth dependency property is of type double . You should set it to a double instead of a GridLength object.

Property Value

Type: System.Double

The minimum width of the element, in device-independent units (1/96th inch per unit). The default value is 0.0. This value can be any value equal to or greater than 0.0. However, PositiveInfinity is not valid, nor is Double.NaN.

I totally assent with bouvierr. I was working on a WPF project and this was something I also run into. Eventually, through the MSDN documentation, I noticed that the code behind concept only accepts double data type as supposed to an integer.

textBox.SetValue(HeightProperty, 120.0);
textBox.SetValue(WidthProperty, 360.0);
textBox.SetValue(FontSizeProperty, 14.0);
textBox.SetValue(MinWidthProperty, 50.0);

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