CtrEditor/ObjetosSim/UserControlFactory.cs

464 lines
18 KiB
C#
Raw Normal View History

using Newtonsoft.Json;
using System.Windows.Controls;
using CtrEditor.Simulacion;
using System.Reflection;
2024-05-31 10:06:49 -03:00
2024-05-23 14:56:14 -03:00
using System.Windows.Data;
using System.Windows;
using System.Windows.Media;
using CtrEditor.ObjetosSim.UserControls;
using System.Collections;
2024-05-31 19:34:58 -03:00
using System.Windows.Input;
using System.Windows.Shapes;
2024-06-02 04:13:01 -03:00
using Xceed.Wpf.Toolkit.PropertyGrid;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using Xceed.Wpf.Toolkit;
using Xceed.Wpf.Toolkit.PropertyGrid.Editors;
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;
}
}
2024-06-02 04:13:01 -03:00
public static void CargarPropiedadesosDatos(object selectedObject, PropertyGrid propertyGrid)
{
// Clear previous properties
propertyGrid.SelectedObject = null;
propertyGrid.PropertyDefinitions.Clear();
// Add properties dynamically based on attributes
var properties = TypeDescriptor.GetProperties(selectedObject)
.Cast<PropertyDescriptor>()
2024-06-04 12:33:00 -03:00
.Where(prop => !prop.Attributes.OfType<HiddenAttribute>().Any()).OrderBy(prop => prop.Name);
2024-06-02 04:13:01 -03:00
foreach (var property in properties)
{
var displayNameAttr = property.Attributes.OfType<DisplayNameAttribute>().FirstOrDefault();
var propertyDefinition = new PropertyDefinition
{
TargetProperties = new[] { property.Name }
};
if (!property.Name.EndsWith("_oculto"))
{
if (displayNameAttr != null)
{
propertyDefinition.DisplayName = displayNameAttr.DisplayName;
}
else
{
propertyDefinition.DisplayName = property.Name.Replace("_", " ");
}
2024-06-04 12:33:00 -03:00
if (property.PropertyType == typeof(double) || property.PropertyType == typeof(float) || property.PropertyType == typeof(string) || property.PropertyType == typeof(int) ||
property.PropertyType == typeof(bool) || property.PropertyType == typeof(Color))
{
propertyGrid.PropertyDefinitions.Add(propertyDefinition);
}
2024-06-02 04:13:01 -03:00
}
}
2024-06-02 04:13:01 -03:00
propertyGrid.SelectedObject = selectedObject;
}
2024-05-31 19:34:58 -03:00
2024-06-02 04:13:01 -03:00
public static void CargarPropiedadesosDatosex(Object selectedObject, StackPanel PanelEdicion, ResourceDictionary Resources)
2024-05-23 14:56:14 -03:00
{
PanelEdicion.Children.Clear();
2024-05-31 19:34:58 -03:00
var properties = selectedObject.GetType().GetProperties().OrderBy(p => p.Name); // Ordenar alfabéticamente
2024-05-23 14:56:14 -03:00
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
2024-05-31 19:34:58 -03:00
{
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(double) || property.PropertyType == typeof(float) || property.PropertyType == typeof(string) || property.PropertyType == typeof(int))
{
var textBox = new TextBox
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
Margin = new Thickness(0),
MinWidth = 200,
VerticalContentAlignment = VerticalAlignment.Center
2024-05-23 14:56:14 -03:00
};
2024-05-31 19:34:58 -03:00
var binding = new Binding(property.Name)
{
Source = selectedObject,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.LostFocus
};
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
if (property.PropertyType == typeof(float))
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
if (Application.Current.Resources.Contains("floatFormatter"))
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
binding.Converter = Application.Current.Resources["floatFormatter"] as IValueConverter;
}
}
if (property.PropertyType == typeof(double))
{
if (Application.Current.Resources.Contains("doubleFormatter"))
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
binding.Converter = Application.Current.Resources["doubleFormatter"] as IValueConverter;
}
}
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
textBox.SetBinding(TextBox.TextProperty, binding);
textBox.KeyDown += (sender, e) =>
{
if (e.Key == Key.Enter || e.Key == Key.Down)
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
var request = new TraversalRequest(FocusNavigationDirection.Next);
request.Wrapped = true;
textBox.MoveFocus(request);
2024-05-23 14:56:14 -03:00
}
2024-05-31 19:34:58 -03:00
else if (e.Key == Key.Up)
2024-05-25 07:53:34 -03:00
{
2024-05-31 19:34:58 -03:00
var request = new TraversalRequest(FocusNavigationDirection.Previous);
request.Wrapped = true;
textBox.MoveFocus(request);
2024-05-25 07:53:34 -03:00
}
2024-05-31 19:34:58 -03:00
};
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
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
};
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
var binding = new Binding(property.Name)
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
Source = selectedObject,
Mode = BindingMode.TwoWay
};
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
checkBox.SetBinding(CheckBox.IsCheckedProperty, binding);
checkBox.KeyDown += (sender, e) =>
{
if (e.Key == Key.Enter || e.Key == Key.Down)
{
var request = new TraversalRequest(FocusNavigationDirection.Next);
request.Wrapped = true;
checkBox.MoveFocus(request);
}
else if (e.Key == Key.Up)
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
var request = new TraversalRequest(FocusNavigationDirection.Previous);
request.Wrapped = true;
checkBox.MoveFocus(request);
}
};
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
Grid.SetColumn(checkBox, 1);
grid.Children.Add(checkBox);
}
else if (property.PropertyType == typeof(Brush))
{
var comboBox = new ComboBox
{
ItemsSource = new List<Tuple<string, SolidColorBrush>>
{
Tuple.Create("Rojo", Brushes.Red),
Tuple.Create("Azul", Brushes.Blue),
Tuple.Create("Negro", Brushes.Black),
Tuple.Create("Verde", Brushes.Green),
Tuple.Create("Gris", Brushes.Gray)
},
SelectedValuePath = "Item2",
Margin = new Thickness(0),
MinWidth = 200
};
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
var binding = new Binding(property.Name)
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
Source = selectedObject,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
comboBox.SetBinding(ComboBox.SelectedValueProperty, binding);
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
comboBox.KeyDown += (sender, e) =>
{
if (e.Key == Key.Enter || e.Key == Key.Down)
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
var request = new TraversalRequest(FocusNavigationDirection.Next);
request.Wrapped = true;
comboBox.MoveFocus(request);
}
else if (e.Key == Key.Up)
2024-05-23 14:56:14 -03:00
{
2024-05-31 19:34:58 -03:00
var request = new TraversalRequest(FocusNavigationDirection.Previous);
request.Wrapped = true;
comboBox.MoveFocus(request);
}
};
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
var template = new DataTemplate();
var stackPanelFactory = new FrameworkElementFactory(typeof(StackPanel));
stackPanelFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
var rectangleFactory = new FrameworkElementFactory(typeof(Rectangle));
rectangleFactory.SetValue(Rectangle.WidthProperty, 16.0);
rectangleFactory.SetValue(Rectangle.HeightProperty, 16.0);
rectangleFactory.SetBinding(Rectangle.FillProperty, new Binding("Item2"));
stackPanelFactory.AppendChild(rectangleFactory);
var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
textBlockFactory.SetBinding(TextBlock.TextProperty, new Binding("Item1"));
stackPanelFactory.AppendChild(textBlockFactory);
template.VisualTree = stackPanelFactory;
comboBox.ItemTemplate = template;
Grid.SetColumn(comboBox, 1);
grid.Children.Add(comboBox);
2024-05-23 14:56:14 -03:00
}
2024-05-31 19:34:58 -03:00
PanelEdicion.Children.Add(grid);
2024-05-23 14:56:14 -03:00
}
2024-05-31 19:34:58 -03:00
}
2024-05-23 14:56:14 -03:00
2024-05-31 19:34:58 -03:00
public static List<string> CargarPropiedadesosDatosTags(Object selectedObject, StackPanel PanelEdicion, ResourceDictionary Resources)
2024-05-23 14:56:14 -03:00
{
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);
2024-05-25 07:53:34 -03:00
if (property.PropertyType == typeof(double) || property.PropertyType == typeof(float) || property.PropertyType == typeof(string) || property.PropertyType == typeof(int))
2024-05-23 14:56:14 -03:00
{
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"];
}
2024-05-25 07:53:34 -03:00
if (property.PropertyType == typeof(double))
{
if (Resources != null)
binding.Converter = (DoubleToFormattedStringConverter)Resources["doubleFormatter"];
}
2024-05-23 14:56:14 -03:00
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;
}
}
}
2024-05-23 14:56:14 -03:00