为什么我不能在 .net core 中将静态属性与通知绑定? [英] Why I can't bind static property with notification in .net core?
本文介绍了为什么我不能在 .net core 中将静态属性与通知绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近我需要在 .Net5 中绑定一个静态属性.我遵循了 http://10rem.net/blog/2011/11/29/wpf-45-binding-and-change-notification-for-static-properties 来实现这一点.
These days I need to bind a static property in .Net5. I followed the tutorial in http://10rem.net/blog/2011/11/29/wpf-45-binding-and-change-notification-for-static-properties to achieve this.
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没有任何变化.
After the program ran, in spite of the value changed, the UI doesn't change any.
我的代码有什么问题?谢谢.
What's wrong with my code? Thank you.
推荐答案
您的绑定语法错误.如果您使用正确的语法(如您所引用的文章中所示),则它可以正常工作:
Your binding syntax is wrong. If you use the correct syntax, shown in the article you are referencing, it works fine:
<TextBlock Text="{Binding Path=(local:MainWindow.ResultText)}"/>
这篇关于为什么我不能在 .net core 中将静态属性与通知绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文