【问题标题】:Why I can't bind static property with notification in .net core?为什么我不能在 .net 核心中将静态属性与通知绑定?
【发布时间】:2021-09-27 14:18:08
【问题描述】:

这些天我需要在 .Net5 中绑定一个静态属性。我按照http://10rem.net/blog/2011/11/29/wpf-45-binding-and-change-notification-for-static-properties 中的教程来实现这一点。

XAML:

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Text="{Binding Source={x:Static local:MainWindow.ResultText}}"></TextBlock>
        <Button Grid.Row="1" Click="Button_Click">Add</Button>
    </Grid>
</Window>

代码隐藏:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        static string _ResultText = "0";
        public static string ResultText
        {
            get => _ResultText; set
            {
                _ResultText = value;
                NotifyStaticPropertyChanged("ResultText");
            }
        }
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int i = Convert.ToInt32(_ResultText)+1;
            ResultText = i.ToString() ;
        }
        public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
        private static void NotifyStaticPropertyChanged(string propertyName)
        {
            if (StaticPropertyChanged != null)
                StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
        }
    }
}

程序运行后,尽管值改变了,但 UI 没有任何变化。

我的代码有什么问题?谢谢。

【问题讨论】:

    标签: c# wpf xaml .net-core


    【解决方案1】:

    您的绑定语法错误。如果您使用正确的语法,如您所引用的文章中所示,它可以正常工作:

    <TextBlock Text="{Binding Path=(local:MainWindow.ResultText)}"/>
    

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 2021-12-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 2011-06-20
      相关资源
      最近更新 更多