WPF Datatrigger no se activa cuando se esperaba
-
01-07-2019 - |
Pregunta
Tengo el siguiente XAML:
<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Margin="0,0,5,0"/>
<TextBlock Text="items selected">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
<Setter Property="TextBlock.Text" Value="item selected"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
El primer bloque de texto cambia felizmente con SelectedItems.Count, mostrando 0,1,2, etc.El disparador de datos en el segundo bloque nunca parece activarse para cambiar el texto.
¿Alguna idea?
Solución
El DataTrigger se está activando, pero el campo Texto de su segundo TextBlock está codificado como "elementos seleccionados", por lo que no podrá cambiar.Para verlo activarse, puede eliminar Text="elementos seleccionados".
Su problema es un buen candidato para usar un Convertidor de valores en lugar de Activador de datos.A continuación se explica cómo crear y utilizar ValueConverter para que establezca el Texto según lo que desee.
Cree este ValueConverter:
public class CountToSelectedTextConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((int)value == 1)
return "item selected";
else
return "items selected";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
Agregue la referencia del espacio de nombres al ensamblaje donde se encuentra el convertidor:
xmlns:local="clr-namespace:ValueConverterExample"
Agregue el convertidor a sus recursos:
<Window.Resources>
<local:CountToSelectedTextConverter x:Key="CountToSelectedTextConverter"/>
</Window.Resources>
Cambie su segundo bloque de texto a:
<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count, Converter={StaticResource CountToSelectedTextConverter}}"/>
Otros consejos
Alternativamente, puedes reemplazar tu XAML con esto:
<TextBlock Margin="0,0,5,0" Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}"/>
<TextBlock>
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="items selected"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
<Setter Property="Text" Value="item selected"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
Los convertidores pueden resolver muchos problemas de vinculación, pero tener muchos convertidores especializados resulta muy complicado.