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(); } } }
结果如下:
示例代码下载:下载
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2016-09-19 3des用法示例,已测试
2016-09-19 制作Windows服务项目详细攻略
2016-09-19 利用好压在C#程序里实现RAR格式的压缩和解压功能
2016-09-19 winform里textBox无法获得焦点的解决方案