WPF 后台數據觸發改變界面狀態-心跳實現


今年做的一個上位機工控WPF項目,做個小小的總結把,以后隨時來找

請不要帶血亂噴,我只是菜鳥.___by 鮑隊

 

類似於這樣子的;大致的意思是:一個代碼變量,通過改變變量的值,綁定這個變量的這個圓顏色也在變化 就是一種心跳效果

在網上數據觸發的感覺不多,廢了不少時間,這里做個總結

1:通知

class NotifyBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanegd(string propertyName)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

class NotifyModels:NotifyBase 
    {
        private bool heartBeat;

        public bool HeartBeat
        {
            get { return heartBeat; }
            set { heartBeat = value;
            OnPropertyChanegd("HeartBeat");
            }
        }        
    }

第一個就不用說了,通知的基類,

第二個是我需要的數據,就是bool類型的心跳(平常可以檢測與下位機其他通信軟件的通信狀態,直觀)

2:矩形的代碼

這個數據觸發 Binding="{Binding HeartBeat}" 綁定了后台DataContext的心跳

改變進行對應的樣式改變;我用的是bool型,所以用的True/False;看類似int也可以

 <Ellipse x:Name="ellStatus"  VerticalAlignment="Center" HorizontalAlignment="Center"     MinHeight="50" MinWidth="50" MaxHeight="50" MaxWidth="50"  >
            <Ellipse.Style >
                <Style TargetType="{x:Type Ellipse}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding HeartBeat}" Value="True"> <Setter Property="Shape.Fill" Value="Red"/> </DataTrigger> <DataTrigger Binding="{Binding HeartBeat}" Value="False"> <Setter Property="Shape.Fill" Value="White"/> </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Ellipse.Style>
        </Ellipse>

 

 

3:后台的代碼

利用一個計時器改變通知里面的值

賦給

 ellStatus.DataContext = models; 
就完成了
public partial class MainWindow : Window
    {
        NotifyModels models;
        private System.Timers.Timer timer;
        public MainWindow()
        {
            InitializeComponent();
            models = new NotifyModels();
           ellStatus.DataContext = models; 
            timer = new System.Timers.Timer(1000);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Enabled = true;
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            models.HeartBeat = !models.HeartBeat;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM