如何比较登录的用户名与DataTrigger

本文关键字:用户 DataTrigger 登录 何比较 比较 | 更新日期: 2023-09-27 17:50:30

我试图比较XAML中登录的用户名。我将其设置在代码后面的变量与"System.Threading.Thread.CurrentPrincipal.Identity.Name",我试图将其设置为DataTrigger中的值,但Visual Studio告诉我,我不能在DataTrigger值中使用Binding,只能在DependencyPropertyDependencyObject中使用。

我试了一千种方法,但我总是得到同样的错误。任何想法?

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>

如何比较登录的用户名与DataTrigger

您可以使用计算true/false的BindingConverter,并使用此true/false作为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();
    }

你可以把usuarioactual变量改成DependencyProperty

public Amigos()
{
    InitializeComponent();
    presenter = new PresenterAmigos(this);
    presenter.ObtenerAmistades();
    presenter.ObtenerUsuarioActual();
    usuarioactual = System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
public string usuarioactual
{
    get { return (string)GetValue(usuarioactualProperty); }
    set { SetValue(usuarioactualProperty, value); }
}
// Using a DependencyProperty as the backing store for usuarioactual.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty usuarioactualProperty =
    DependencyProperty.Register("usuarioactual", typeof(string), typeof(Amigos), new UIPropertyMetadata(string.Empty));