Подтвердить что ты не робот

Как я могу вставить в ObservableCollection <объект>

Как я могу сделать

from ObservableCollection<TabItem> into ObservableCollection<object>

это не работает для меня

(ObservableCollection<object>)myTabItemObservableCollection
4b9b3361

Ответ 1

вы должны скопировать, как это

return new ObservableCollection<object>(myTabItemObservableCollection);

Ответ 2

В принципе, вы не можете. Не сейчас, и не в .NET 4.0.

Каков контекст здесь? Что тебе нужно? LINQ имеет Cast<T>, который может предоставить вам данные в виде последовательности или есть некоторые трюки с общими методами (т.е. Foo<T>(ObservalbleCollection<T> col) и т.д.).

Или вы можете просто использовать не-общий IList?

IList untyped = myTypedCollection;
untyped.Add(someRandomObject); // hope it works...

Ответ 3

вы можете использовать IEnumerable.Cast<T>()

Ответ 4

Вы не можете. ObservableCollection<TabItem> не выводится из ObservableCollection<object>.

Если вы объясните, почему вы хотите, возможно, мы можем указать альтернативный интерфейс, который вы можете использовать.

Ответ 5

thanx для всех ответов, но я думаю, что я решил эту проблему самостоятельно с помощью "helpermethode".

Возможно, для этого есть лучший метод или инструкция linq.

private void ConvertTabItemObservableCollection()
{
  Manager manager = this.container.Resolve<Manager>();
  foreach (var tabItem in manager.ObjectCollection)
  {
    TabItemObservableCollection.Add((TabItem)tabItem);
  }
}

Ответ 6

Ни один из примеров, которые я нашел, не работал у меня, я объединил приведенный ниже код и, похоже, сработал. У меня есть иерархия, созданная десериализацией XML файла, и я могу перебирать все объекты в иерархии, но вы можете адаптировать это, чтобы просто пропустить один ObservableCollection и получить объекты как объекты, а не строго типизированные.

Я хочу добавить PropertyChangingEventHandler для каждого свойства в иерархии, чтобы я мог реализовать функциональные возможности отмены/повтора.

public static class TraversalHelper
{

    public static void TraverseAndExecute(object node)
    {
        TraverseAndExecute(node, 0);
    }

    public static void TraverseAndExecute(object node, int level)
    {
        foreach (var property in node.GetType().GetProperties())
        {
            var propertyValue = node.GetType().GetProperty(property.Name).GetGetMethod().Invoke(node, null); // Get the value of the property
            if (null != propertyValue)
            {
                Console.WriteLine("Level=" + level + " :  " + property.Name + " :: " + propertyValue.GetType().Name); // For debugging
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(ObservableCollection<>)) // Check if we are dealing with an observable collection
                {
                    //var dummyvar = propertyValue.GetType().GetMethods();   // This was just used to see which methods I could find on the Collection
                    Int32 propertyValueCount = (Int32)propertyValue.GetType().GetMethod("get_Count").Invoke(propertyValue, null); // How many objects in the collection
                    level++;
                    for (int i = 0; i < propertyValueCount; i++) // Loop over all objects in the Collection
                    {
                        object properyValueObject = (object)propertyValue.GetType().GetMethod("get_Item").Invoke(propertyValue, new object[] { i }); // Get the specified object out of the Collection
                        TraverseAndExecute(properyValueObject, level); // Recursive call in case this object is a Collection too
                    }
                }
            }
        }
    }
}

Метод называется так

TraversalHelper.TraverseAndExecute(object);

Если вы просто хотите создать коллекцию объектов, вам нужен только этот бит кода

ObservableCollection<Field> typedField = migration.FileDescriptions[0].Inbound[0].Tables[0].Table[0].Fields[0].Field; // This is the strongly typed decalaration, a collection of Field objects
object myObject = typedField; // Declare as object
Int32 propertyValueCount = (Int32)myObject.GetType().GetMethod("get_Count").Invoke(myObject, null); // How many objects in this Collection
for (int i = 0; i < propertyValueCount; i++) // Loop over all objects in the Collection
{
    object properyValueObject = (object)myObject.GetType().GetMethod("get_Item").Invoke(myObject, new object[] { i }); // Get the specified object out of the Collection, in this case a Field object
    // Add the object to a collection of objects, or whatever you want to do with object
}

Ответ 7

Вы можете привести его как INotifyCollectionChanged;

Подобно:

if (myTabItemObservableCollection is INotifyCollectionChanged collection)
{
   Do Stuff
}