我需要一种用户输入的表格。所以我创建了一个具有定义列和行的网格。 该表格不是用于显示数据,其目的只是为了结构化输入。
为了结构化所有元素(如文本框等),我定义了所有列的宽度。将会有几个网格在堆栈面板中对齐。
XAML中的列定义如下:
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="widthLoopID" Width="55" />
</Grid.ColumnDefinition>
我参考了其他网格,比如:
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ElementName=widthLoopID, Path=Width}" />
</GridColumnDefinition>
那很好用。
现在是困难的部分。我如何在代码后端做到这一点?
我尝试了以下内容:
// define columns
ColumnDefinition loopIdColumn = new ColumnDefinition();
// setup databinding for columns
Binding loopIdBinding = new Binding();
// set binding for width
loopIdBinding.ElementName = "widthLoopID";
loopIdBinding.Path = new PropertyPath("Width");
loopIdColumn.SetBinding(Grid.WidthProperty, loopIdBinding);
// add definition of column
loopGrid.ColumnDefinitions.Add(loopIdColumn);
但是当执行时,我得到了以下错误:
System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'System.Windows.GridLength' and 'System.Double'. Consider using Converter property of Binding. BindingExpression:Path=Width; DataItem='ColumnDefinition' (HashCode=37457626); target element is 'ColumnDefinition' (HashCode=7871588); target property is 'Width' (type 'Double')
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='55' BindingExpression:Path=Width; DataItem='ColumnDefinition' (HashCode=37457626); target element is 'ColumnDefinition' (HashCode=7871588); target property is 'Width' (type 'Double')
所以我需要转换 “Width” ,但是我该如何做,为什么默认转换器不能像在 XAML 中那样执行?
我对 WPF 还不太了解,可能没有理解每个概念,请给我一点提示。
提前感谢您 Benny
编辑:
我尝试了第一个答案的提示。 它不起作用,因为 GridLengthConverter 不是 IValueConverter 类型。
所以我写了一个双向 GridLength 转 Double 的转换器。
现在值已经被转换了,但结果与代码在 XAML 中执行的结果不同。 我觉得它根本无法从代码中运行。 真奇怪。
这是转换器的代码:
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Globalization;
using System.Diagnostics;
namespace editor
{
[ValueConversion(typeof(Double), typeof(GridLength))]
class DoubleToGridLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// check whether a value is given
if (value != null)
{
Debug.WriteLine("value is: " + value + " type: " + value.GetType());
return (Double)((GridLength)(value)).Value;
}
else
{
throw new ValueUnavailableException();
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// check whether a value is given
if (value != null)
{
return new GridLength((Double)value);
}
else
{
throw new ValueUnavailableException();
}
}
}
}
还有什么线索吗?我可以想象其他人可能已经遇到过这个问题。
再次感谢 Benny