Mi enlace de datos con el convertidor de valor no funciona
-
20-08-2019 - |
Pregunta
Tengo una clase de elemento simple, que se ve así:
public class Item : DependencyObject
{
public int No
{
get { return (int)GetValue(NoProperty); }
set { SetValue(NoProperty, value); }
}
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public static readonly DependencyProperty NoProperty = DependencyProperty.Register("No", typeof(int), typeof(Item));
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Item));
}
Y un ValueConverter, que se ve así:
[ValueConversion(typeof(Item), typeof(string))]
internal class ItemToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return null;
}
var item = ((Item)value);
var sb = new StringBuilder();
sb.AppendFormat("Item # {0}", item.No);
if (string.IsNullOrEmpty(item.Name) == false)
{
sb.AppendFormat(" - [{0}]", item.Name);
}
return sb.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
En mi ventana WPF, declaro una DependencyProperty (llamada Items) que contiene una lista de objetos Item (List < Item >) y crea un ComboBox que se une a esta DependencyProperty usando este XAML- código:
<ComboBox ItemsSource="{Binding ElementName=mainWindow, Path=Items}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource itemToStringConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Si ejecuto el siguiente código una vez, el enlace de datos funciona bien, sin embargo, cada conversión de valor falla si lo ejecuto nuevamente:
var item1 = new Item {Name = "Item A", No = 1};
var item2 = new Item {Name = "Item B", No = 2};
var item3 = new Item {Name = "Item C", No = 3};
Items = new List<Item> {item1, item2, item3};
El problema es que el método ItemToStringConverter.Convert ahora pasa un string-object como primer parámetro en lugar de un Item-object?
¿Qué estoy haciendo mal?
Saludos, Kenneth
Solución
Una solución simple sería verificar el tipo pasado a su ValueConverter. Cambie el método Convertir de la siguiente manera:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
var item = value as Item;
if(item == null) { return null; }
var sb = new StringBuilder();
sb.AppendFormat("Item # {0}", item.No);
if(string.IsNullOrEmpty(item.Name) == false) {
sb.AppendFormat(" - [{0}]", item.Name);
}
return sb.ToString();
}
Otros consejos
Enfoque alternativo,
- Puede derivar su clase de Object en lugar de DependencyObject
- Puede implementar la interfaz INotifyPropertyChange
- Y puede implementar una propiedad de solo lectura y un evento de notificación de incendio cuando cambie No o Nombre.
Elemento de clase pública: System.ComponentModel.INotifyPropertyChanged {
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void Notify(string p)
{
if (PropertyChanged != null)
PropertyChanged(this,
new System.ComponentModel.PropertyChangedEventArgs(p));
}
private int _No = 0;
public int No
{
get
{
return _No;
}
set
{
_No = value;
Notify("No");
Notify("DisplayName");
}
}
private string _Name = "";
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
Notify("Name");
Notify("DisplayName");
}
}
public string DisplayName
{
get
{
string sb = string.Format("Item # {0}", _No);
if (!string.IsNullOrEmpty(_Name))
sb += _Name;
return sb;
}
}
}
Ahora solo puede enlazar " DisplayName " propiedad en lugar de convertidor ..
- Los convertidores son bastante complejos de implementar
- Y las clases basadas en DependencyObject solo deben usarse para fines de IU
Si desea utilizar el enlace de datos, debe asignar su colección a ItemsSource, no a Items. Creo que eso probablemente solucionaría este problema.