Search code examples
c#wpfxamldata-bindingcode-behind

How to compare the logged username with DataTrigger


I'm trying to compare the name of the logged username in XAML. I set it in codebehind in a variable with "System.Threading.Thread.CurrentPrincipal.Identity.Name" and I'm trying to set it as a value in a DataTrigger, but Visual Studio tells me that I can't use Binding in a DataTrigger Value, only in a DependencyProperty or DependencyObject.

I've tried one thousand ways but I always get the same error. Any idea?

public string usuarioactual;

public Amigos()
{
    InitializeComponent();
    presenter = new PresenterAmigos(this);
    presenter.ObtenerAmistades();
    presenter.ObtenerUsuarioActual();
    usuarioactual = System.Threading.Thread.CurrentPrincipal.Identity.Name;

}


<Style.Triggers>
    <DataTrigger Binding="{Binding Recibida.Email}" Value="{Binding usuarioactual}">
        <Setter Property="Content" Value="{Binding Enviada.Email}"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding Enviada.Email}" Value="{Binding usuarioactual}">
        <Setter Property="Content" Value="{Binding Recibida.Email}"/>
    </DataTrigger>
</Style.Triggers>

Solution

  • You can use BindingConverter that evaluates to true/false and use thistrue/false as value condition in DataTrigger.

    public class UserNameToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var username = (string)value;
            if (username == "System.Threading.Thread.CurrentPrincipal.Identity.Name")
              return true;
            return false;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }