1. 程式人生 > 實用技巧 >WPF繫結靜態變數的教程

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();
        }
    }
}

結果如下:

示例程式碼下載:下載