我有一个表示列宽的值数组。我试图在网格中绑定这些值,使显示的列宽与数组匹配。问题是,我不能使用显式索引(例如[0],1),因为列数会动态变化。我发现this问题建议使用MultiBinding让我使用动态索引。添加列时,这为我提供了以下代码:
while (mGrid.ColumnDefinitions.Count < maxColCount)
{
ColumnDefinition colDef = new ColumnDefinition();
int newIdx = mGrid.ColumnDefinitions.Count;
if(ColumnWidths.Count > newIdx)
{
if(ColumnWidths[newIdx].Value < 0)
ColumnWidths[newIdx] = DefaultColumnWidth;
MultiBinding bind = new MultiBinding();
bind.Converter = mHeightWidthConverter;
bind.Bindings.Add(new Binding("ColumnWidths"));
bind.Bindings.Add(new Binding { Source = newIdx });
bind.Mode = BindingMode.TwoWay;
colDef.SetBinding(ColumnDefinition.WidthProperty, bind);
}
else
colDef.Width= DefaultColumnWidth;
mGrid.ColumnDefinitions.Add(colDef);
}
使用转换器:
public class HeightWidthConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if(values == null || values.Length < 2)
return null;
ObservableCollection<GridLength> array = values[0] as ObservableCollection<GridLength>;
int index = (int)values[1];
if(array.Count > index)
return array[index];
else
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
这适用于单向绑定,但我需要twoway绑定。看看转换的ConvertBack函数,我无法弄清楚如何将“value”分配给原始数组的正确元素。
建议?