CtrEditor/ObjetosSim/UserControlFactory.cs

352 lines
14 KiB
C#

using Newtonsoft.Json;
using System.Windows.Controls;
using CtrEditor.Simulacion;
using System.Reflection;
using CtrEditor.Convertidores;
using System.Windows.Data;
using System.Windows;
using System.Windows.Media;
using CtrEditor.ObjetosSim.UserControls;
using System.Collections;
namespace CtrEditor.ObjetosSim
{
public static class UserControlFactory
{
public static UserControl? GetControlForType(Type tipoObjeto)
{
// Obtener el nombre del tipo de objeto
string typeName = tipoObjeto.Name;
// Cambiar las primeras dos letras de 'os' a 'uc'
if (typeName.StartsWith("os"))
{
string newTypeName = "uc" + typeName.Substring(2);
// Obtener el ensamblado donde se encuentra el tipo UserControl
Assembly assembly = Assembly.GetExecutingAssembly();
// Buscar el tipo en los ensamblados cargados
Type? controlType = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.FirstOrDefault(t => t.Name == newTypeName);
if (controlType != null && typeof(UserControl).IsAssignableFrom(controlType))
{
// Crear una instancia del tipo encontrado
return (UserControl?)Activator.CreateInstance(controlType);
}
}
return null;
}
public static osBase? GetInstanceForType(Type tipoObjeto)
{
// Verifica si el tipo pasado es un subtipo de osBase
if (!typeof(osBase).IsAssignableFrom(tipoObjeto))
{
throw new ArgumentException("El tipo pasado no es un subtipo de osBase", nameof(tipoObjeto));
}
// Crear una instancia del tipo especificado
return (osBase?)Activator.CreateInstance(tipoObjeto);
}
public static osBase? CreateInstanceAndPopulate(Type tipoObjeto, string jsonString)
{
osBase? instance = GetInstanceForType(tipoObjeto);
if (instance != null)
{
// Deserializa los datos desde jsonString y popula la instancia
JsonConvert.PopulateObject(jsonString, instance);
}
return instance;
}
public static void AssignDatos(UserControl userControl, osBase datos, SimulationManagerFP simulationManager)
{
if (userControl is IDataContainer dataContainer)
{
dataContainer.Datos = datos;
userControl.DataContext = datos;
datos.VisualRepresentation = userControl;
datos.simulationManager = simulationManager;
}
}
public static void CargarPropiedadesosDatos(Object selectedObject, StackPanel PanelEdicion, ResourceDictionary Resources)
{
PanelEdicion.Children.Clear();
var properties = selectedObject.GetType().GetProperties();
foreach (var property in properties)
{
if (Attribute.IsDefined(property, typeof(HiddenAttribute)))
continue;
if (property.Name.EndsWith("_oculto"))
continue;
var grid = new Grid();
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
var label = new Label
{
Content = property.Name.Replace("_", " ") + ":",
Margin = new Thickness(0, 0, 5, 0),
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetColumn(label, 0);
grid.Children.Add(label);
if (property.PropertyType == typeof(float) || property.PropertyType == typeof(string) || property.PropertyType == typeof(int))
{
var textBox = new TextBox
{
Margin = new Thickness(0),
MinWidth = 200,
VerticalContentAlignment = VerticalAlignment.Center
};
var binding = new Binding(property.Name)
{
Source = selectedObject,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.LostFocus
};
if (property.PropertyType == typeof(float))
{
if (Resources != null)
binding.Converter = (FloatToFormattedStringConverter)Resources["floatFormatter"];
}
textBox.SetBinding(TextBox.TextProperty, binding);
Grid.SetColumn(textBox, 1);
grid.Children.Add(textBox);
}
else if (property.PropertyType == typeof(bool))
{
var checkBox = new CheckBox
{
Margin = new Thickness(5, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center
};
var binding = new Binding(property.Name)
{
Source = selectedObject,
Mode = BindingMode.TwoWay
};
checkBox.SetBinding(CheckBox.IsCheckedProperty, binding);
Grid.SetColumn(checkBox, 1);
grid.Children.Add(checkBox);
}
else if (property.PropertyType == typeof(Brush))
{
var listBox = new ListBox
{
ItemsSource = new List<string> { "Rojo", "Azul", "Negro", "Verde", "Gris" },
Margin = new Thickness(0),
MinWidth = 200
};
listBox.SelectionChanged += (sender, e) =>
{
if (listBox.SelectedItem != null)
{
switch (listBox.SelectedItem.ToString())
{
case "Rojo":
property.SetValue(selectedObject, Brushes.Red);
break;
case "Azul":
property.SetValue(selectedObject, Brushes.Blue);
break;
case "Negro":
property.SetValue(selectedObject, Brushes.Black);
break;
case "Verde":
property.SetValue(selectedObject, Brushes.Green);
break;
case "Gris":
property.SetValue(selectedObject, Brushes.Gray);
break;
}
}
};
var binding = new Binding(property.Name)
{
Source = selectedObject,
Mode = BindingMode.TwoWay,
Converter = new BrushToColorNameConverter()
};
listBox.SetBinding(ListBox.SelectedItemProperty, binding);
Grid.SetColumn(listBox, 1);
grid.Children.Add(listBox);
}
PanelEdicion.Children.Add(grid);
}
}
public static List<string> CargarPropiedadesosDatosTags(Object selectedObject, StackPanel PanelEdicion, ResourceDictionary Resources)
{
PanelEdicion.Children.Clear();
var properties = selectedObject.GetType().GetProperties();
List<string> tags = new List<string>();
foreach (var property in properties)
{
if (Attribute.IsDefined(property, typeof(HiddenAttribute)))
continue;
if (property.Name.EndsWith("_oculto"))
continue;
var grid = new Grid();
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
var label = new Label
{
Content = property.Name.Replace("_", " ") + ":",
Margin = new Thickness(0, 0, 5, 0),
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetColumn(label, 0);
grid.Children.Add(label);
if (property.PropertyType == typeof(float) || property.PropertyType == typeof(string) || property.PropertyType == typeof(int))
{
var textBox = new TextBox
{
Margin = new Thickness(0),
MinWidth = 200,
VerticalContentAlignment = VerticalAlignment.Center
};
var binding = new Binding(property.Name)
{
Source = selectedObject,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.LostFocus
};
if (property.PropertyType == typeof(float))
{
if (Resources != null)
binding.Converter = (FloatToFormattedStringConverter)Resources["floatFormatter"];
}
textBox.SetBinding(TextBox.TextProperty, binding);
Grid.SetColumn(textBox, 1);
grid.Children.Add(textBox);
var tagTextBox = new TextBox
{
Margin = new Thickness(0),
MinWidth = 100,
VerticalContentAlignment = VerticalAlignment.Center
};
// Add an empty string to the tags list and get the index
tags.Add(string.Empty);
int tagIndex = tags.Count - 1;
// Event handler to update the tags list when the text changes
tagTextBox.TextChanged += (sender, args) =>
{
tags[tagIndex] = tagTextBox.Text;
};
Grid.SetColumn(tagTextBox, 2);
grid.Children.Add(tagTextBox);
}
else if (property.PropertyType == typeof(bool))
{
var checkBox = new CheckBox
{
Margin = new Thickness(5, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center
};
var binding = new Binding(property.Name)
{
Source = selectedObject,
Mode = BindingMode.TwoWay
};
checkBox.SetBinding(CheckBox.IsCheckedProperty, binding);
Grid.SetColumn(checkBox, 1);
grid.Children.Add(checkBox);
}
else if (property.PropertyType == typeof(Brush))
{
var listBox = new ListBox
{
ItemsSource = new List<string> { "Rojo", "Azul", "Negro", "Verde", "Gris" },
Margin = new Thickness(0),
MinWidth = 200
};
listBox.SelectionChanged += (sender, e) =>
{
if (listBox.SelectedItem != null)
{
switch (listBox.SelectedItem.ToString())
{
case "Rojo":
property.SetValue(selectedObject, Brushes.Red);
break;
case "Azul":
property.SetValue(selectedObject, Brushes.Blue);
break;
case "Negro":
property.SetValue(selectedObject, Brushes.Black);
break;
case "Verde":
property.SetValue(selectedObject, Brushes.Green);
break;
case "Gris":
property.SetValue(selectedObject, Brushes.Gray);
break;
}
}
};
var binding = new Binding(property.Name)
{
Source = selectedObject,
Mode = BindingMode.TwoWay,
Converter = new BrushToColorNameConverter()
};
listBox.SetBinding(ListBox.SelectedItemProperty, binding);
Grid.SetColumn(listBox, 1);
grid.Children.Add(listBox);
}
PanelEdicion.Children.Add(grid);
}
return tags;
}
}
}