【问题标题】:How to compare the logged username with DataTrigger如何将记录的用户名与 DataTrigger 进行比较
【发布时间】:2012-12-18 03:41:42
【问题描述】:

我正在尝试比较 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>

【问题讨论】:

    标签: c# wpf xaml data-binding code-behind


    【解决方案1】:

    您可以使用计算结果为true/falseBindingConverter 并使用thistrue/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();
        }
    

    【讨论】:

      【解决方案2】:

      您可以将 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));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-24
        • 1970-01-01
        • 2020-03-21
        • 2013-07-30
        • 1970-01-01
        • 1970-01-01
        • 2022-01-18
        • 2018-06-24
        相关资源
        最近更新 更多