点击按钮没得textBox中内容不发送改变,跟踪后发现PropertyChanged没有起到作用,各位分析下。
这是 dateModel类代码
using System;
using System.ComponentModel;
using System.Windows.Media;
namespace dateModel
{
public class DateModel:INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private string _value = "我是初始数据,颜色橘色";
private Brush _valueColor = Brushes.Orange;
public Brush ValueColor
{
get { return _valueColor; }
set
{
_valueColor = value;
ChangeEVent("ValueColor");//订阅颜色改变
}
}
public string Value
{
get { return _value; }
set
{
_value = value;
ChangeEVent("Value");//订阅内容改变
if (value == "我是改变数据,颜色红色") ValueColor = Brushes.Red;
}
}
/// <summary>
/// 订阅事件
/// </summary>
/// <param name="name">事件名称</param>
private void ChangeEVent( String name)
{
if (name != "")
{
if (PropertyChanged != null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
}
}
这是MainWindow代码
using dateModel;
using System.Windows;
namespace test
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DateModel? dateModel = null;
public MainWindow()
{
InitializeComponent();
dateModel = new DateModel();
this.DataContext = new DateModel();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
dateModel!.Value = "我是改变数据,颜色红色";
}
}
}
这是xaml代码
<Window x:Class="test.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:test" xmlns:datemodel="clr-namespace:dateModel" d:DataContext="{d:DesignInstance Type=datemodel:DateModel}"
mc:Ignorable="d"
Title="MainWindow" FontSize="40" Height="450" Width="800">
<Grid>
<Button VerticalAlignment="Center" HorizontalAlignment="Right" Width="120" Height="60" Content="修改" Click="Button_Click" />
<TextBox
VerticalAlignment="Center"
HorizontalAlignment="Left"
Width="650"
Text="{Binding Value}"
Foreground="{Binding ValueColor}"
/>
</Grid>
</Window>