加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 当Bool变量变为True时更改标签

发布时间:2020-12-15 23:43:30 所属栏目:百科 来源:网络整理
导读:我真的不确定如何解释这个…我将把代码放在psuedo代码中以便于阅读 当一个类的bool变量发生变化时,我想要一个标签来改变它的文本…我不知道我需要使用什么因为我使用的是WPF而且这个类不能只改变标签我不能我想? 我需要某种活动吗?还是WPF活动?谢谢你的帮
我真的不确定如何解释这个…我将把代码放在psuedo代码中以便于阅读

当一个类的bool变量发生变化时,我想要一个标签来改变它的文本…我不知道我需要使用什么因为我使用的是WPF而且这个类不能只改变标签我不能我想?

我需要某种活动吗?还是WPF活动?谢谢你的帮助

public MainWindow()
{
   SomeClass temp = new SomeClass();

   void ButtonClick(sender,EventArgs e)
   {  
      if (temp.Authenticate)
        label.Content = "AUTHENTICATED";
   }
}

public SomeClass
{
  bool _authenticated;

  public bool Authenticate()
  {
    //send UDP msg
    //wait for UDP msg for authentication
    //return true or false accordingly
  }
}

解决方法

除了BradledDotNet之外的另一种WPF方法是使用触发器.这将是纯粹基于XAML而没有转换器代码.

XAML:

<Label>
  <Label.Style>
    <Style TargetType="Label">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsAuthenticated}" Value="True">
          <Setter Property="Content" Value="Authenticated" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Label.Style>
</Label>

同样的规则适用于BradledDotNet所提到的,应该附加ViewModel并且“IsAuthenticated”属性应该引发PropertyChanged事件.

– 按照Gayot Fow的建议添加一些样板代码 –

查看代码背后:

为简单起见,我将在后面的代码中设置视图的DataContext.为了更好的设计,您可以使用ViewModelLocator,如here所述.

public partial class SampleWindow : Window
{
  SampleModel _model = new SampleModel();

  public SampleWindow() {
    InitializeComponent();
    DataContext = _model; // attach the model/viewmodel to DataContext for binding in XAML
  }
}

示例模型(它应该是ViewModel):

这里的要点是附加的模型/ viewmodel必须实现INotifyPropertyChanged.

public class SampleModel : INotifyPropertyChanged
{
  bool _isAuthenticated = false;

  public bool IsAuthenticated {
    get { return _isAuthenticated; }
    set {
      if (_isAuthenticated != value) {
        _isAuthenticated = value;
        OnPropertyChanged("IsAuthenticated"); // raising this event is key to have binding working properly
      }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  void OnPropertyChanged(string propName) {
    if (PropertyChanged != null) {
      PropertyChanged(this,new PropertyChangedEventArgs(propName));
    }
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读