简体   繁体   English

WPF将int绑定到集合

[英]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. 我有WPF工具包提供的IntegerUpDown,喜欢将其绑定到实体框架自动生成的集合(EntityCollection)。

My intention: i have this UpDown-control to change the number of items in the collection. 我的意图:我有这个UpDown控件来更改集合中的项目数。

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. 我能够使用转换器在IntegerUpDown上显示计数,但无法更改集合中的项目数,因为我无法通过ConvertBack()函数对集合进行控制-使用IValueConverter接口。

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. 因为在ConvertBack()中,模型的集合将被转换器类的修改者覆盖。 This is not possible in EF. 在EF中这是不可能的。 I have to use the model from the EF directly, modifying the items. 我必须直接使用EF中的模型,修改项目。

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: 无论如何,您想要做的是在视图模型中添加MyCollectionCount属性并绑定到该模型:

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

If your control is using databinding, you can pass that into the convert as a parameter: 如果您的控件使用数据绑定,则可以将其作为参数传递给convert:

<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 . 有关Xaml中Converters的更多信息, 请查看MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM