WPF绑定静态变量的教程(一)

一、新建解决方案

  创建一个wpf测试项目

  

   

 二、新建一个静态变量

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace WpfTestBindStaticField
{
    public class StaticList
    {
        /// <summary>
        /// 新建静态属性变更通知
        /// </summary>
        public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
        private static int _testValue = 0;
        public static int TestValue
        {
            get
            {
                return _testValue;
            }
            set
            {
                _testValue = value;
                //调用通知
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(nameof(TestValue)));
            }
        }
    }
}

三、前台给textblock绑定这个变量

<Window x:Class="WpfTestBindStaticField.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTestBindStaticField"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">

    <Window.Resources>
        <local:StaticList x:Key="statisList"/>
    </Window.Resources>
    <Grid>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="60" Text="{Binding Source={StaticResource statisList},Path=TestValue}"/>
    </Grid>
</Window>

四、测试后台改变这个变量

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfTestBindStaticField
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static Random random = new Random();
        private static Timer timer = null;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            timer = new Timer(200);
            timer.Elapsed += (o, f) =>
            {
                StaticList.TestValue = random.Next(0, 1000);
            };
            timer.Start();
        }
    }
}

结果如下:

 

 

示例代码下载:下载

posted @ 2020-09-19 13:06  星星c#  阅读(6936)  评论(0编辑  收藏  举报