¿Cómo puedo echar en un ObservableCollection
-
20-09-2019 - |
Pregunta
¿Cómo puedo enviar contenido
from ObservableCollection<TabItem> into ObservableCollection<object>
Esto no funciona para mí
(ObservableCollection<object>)myTabItemObservableCollection
Solución
debería copiar como esto
return new ObservableCollection<object>(myTabItemObservableCollection);
Otros consejos
Básicamente, no se puede. Ahora no, y no en .NET 4.0 .
¿Cuál es el contexto aquí? ¿Que necesitas? LINQ tiene Cast<T>
que pueden obtener los datos como un secuencia , o hay algunos trucos con métodos genéricos (es decir Foo<T>(ObservalbleCollection<T> col)
etc).
O puede simplemente utilizar el IList
no genérico?
IList untyped = myTypedCollection;
untyped.Add(someRandomObject); // hope it works...
podría utilizar IEnumerable.Cast<T>()
No se puede. ObservableCollection<TabItem>
no deriva de ObservableCollection<object>
.
Si usted explica por qué desea que tal vez podemos señalar una interfaz alternativa que puede utilizar.
gracias por todas las respuestas, pero creo que tengo resolver este mismo problema con un "helpermethode".
Tal vez tiene ninguna un mejor método o una declaración de LINQ para esto.
private void ConvertTabItemObservableCollection()
{
Manager manager = this.container.Resolve<Manager>();
foreach (var tabItem in manager.ObjectCollection)
{
TabItemObservableCollection.Add((TabItem)tabItem);
}
}
Ninguno de los ejemplos que he encontrado han trabajado para mí, he improvisado el código abajo y parece que funciona. Tengo una jerarquía que se crea por deserializar un archivo XML y soy capaz de recorrer todos los objetos de la jerarquía, pero se puede adaptar esta a tan solo conecta a través de una ObservableCollection y obtener los objetos como objetos y no inflexible de tipos.
Quiero añadir un PropertyChangingEventHandler a cada propiedad en la jerarquía de modo que pueda implementar la funcionalidad de deshacer / rehacer.
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
}
}
}
}
}
}
El método se llama así simplemente
TraversalHelper.TraverseAndExecute(object);
Si lo que desea es crear una colección de objetos que sólo tiene este fragmento de código
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
}
Puede moldeada como INotifyCollectionChanged;
Al igual que:
if (myTabItemObservableCollection is INotifyCollectionChanged collection)
{
Do Stuff
}