geskill
geskill

Reputation: 307

WPF Binding a int to collection

I have the IntegerUpDown from the WPF Toolkit and like to bind this to auto generated collection (EntityCollection) from the entity-framework.

My intention: i have this UpDown-control to change the number of items in the collection.

I was able to use a converter to display the Count at the IntegerUpDown, but not to change the number of items in the collection because i had no control over the collection at ConvertBack()-function - using a IValueConverter interface.

EDIT:

However i cannot use a converter to solve this problem accurately. Because in ConvertBack() the collection from the model will be overrided with the modified from converter class. This is not possible in EF. I have to use the model from the EF directly, modifying the items.

Upvotes: 0

Views: 291

Answers (2)

Anton Tykhyy
Anton Tykhyy

Reputation: 20076

A collection with settable Count? That's rather unusual! Anyway, what you want to do is add a MyCollectionCount property to your viewmodel and bind to that:

public int MyCollectionCount
{
    get { return Model.MyCollection != null ? Model.MyCollection.Count : 0 ; }
    set { if    (Model.MyCollection != null)  
                 Model.MyCollection.Count = value ; /* ¬_¬ */ }
}

Upvotes: 2

Will Custode
Will Custode

Reputation: 4604

If your control is using databinding, you can pass that into the convert as a parameter:

<IntegerUpDown  Value="{Binding MyCollection,
                Converter={StaticResource CollectionConverter},
                ConverterParameter=MyCollection}" />

And use this as your converter:

public class UpDownConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        ICollection<Type> col = (ICollection<Type>)value;

        return col.Count;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        ICollection<Type> col = (ICollection<Type>)parameter;

        // Do manipulation here
    }
}

For more info on Converters in Xaml, check out the MSDN.

Upvotes: 1

Related Questions