千梦一生 2019-09-30 14:18 采纳率: 100%
浏览 381
已采纳

Wpf INotifyPropertyChanged实现双向绑定的小测试。似乎是绑定失败。请教一下代码是哪里没有写对呢?

学习后尝试练习一下发现 Test的事件PropertyChanged始终为空。请问一下我写的代码哪里需要修改呢,现在的问题是什么原因。我感觉是自己binding 的path没写对,或者是datacontext没对。因为这两个我不知道该怎样写,该写在哪里?

<Window x:Class="WpfApplication3.MainWindow"
        Name="winM"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock x:Name="txt2" Background="Yellow" Text="{Binding Path = this.A , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" Margin="33,127,32,92" />
        <Button Content="Button" HorizontalAlignment="Left" Margin="140,263,0,0" VerticalAlignment="Top" Width="115" Height="47" Click="Button_Click"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="334,263,0,0" VerticalAlignment="Top" Width="115" Height="43" Click="Button_Click_1"/>
    </Grid>
</Window>

//cs代码

namespace WpfApplication3
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {

            InitializeComponent();

            test = new Test();
            this.txt2.DataContext = test;

        }
        public Test test;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            test.A = "1111111111";
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            test.A = "22222222222";
        } 

    }
    public class Test : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string a;
        public string A
        {
            get { return a; }
            set
            {
                a = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("A"));
                }
            }
        }
    }
}
  • 写回答

2条回答 默认 最新

  • 关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)