千梦一生 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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?