简体   繁体   中英

BindingList with int array updating a listbox?

I have a BindingList like the follow:

private BindingList<int[]> sortedNumbers = new BindingList<int[]>();

Each entry is a int[6], now I wanted to bind it to a listbox so it updates it everytime a set of numbers is added to it.

listBox1.DataSource = sortedNumbers;

The result is the below text for each entry:

Matriz Int32[].

How do I format the output or change it so it prints the numbers of each entry set as they are generated ?

You need to handle the Format event:

listBox1.Format += (o,e) => 
 { 
    var array = ((int[])e.ListItem).Select(i=>i.ToString()).ToArray();
    e.Value = string.Join(",", array);
 };

How about using IValueConverter in the ItemTemplate?

<ListBox x:Name="List1" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Converter={StaticResource  NumberConverter}}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

public class NumberConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is int[])
        {
            int[] intValues = (int[])value;
            return String.Join(",", intValues);
        }
        else return Binding.DoNothing;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Convert(value, targetType, parameter, culture);
    }
}

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