I have an array of values representing columns widths. I am trying to bind those values within a grid such that the displayed column widths match the array. The problem is, I can't use explicit indexing (e.g. [0], 1) since the number of columns will change dynamically. I found this question which suggests using a MultiBinding to let me use dynamic indexing. This gives me the following code when a column is added:
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);
}
with the converter:
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();
}
}
This works well for oneway binding but I need twoway binding. Looking at the ConvertBack function of the convert, I can't figure out how to get that to assign "value" to the correct element of the original array.
Suggestions?
object[] originalValuesas a property on your Converter and then when you convert back return originalValues. remember though to add the item to the originalValues when you convert them. I hope I'm clear enough HTH.