WPF 数据绑定没有更新? [英] WPF DataBinding not updating?

查看:58
本文介绍了WPF 数据绑定没有更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,我将复选框的 IsChecked 属性与代码隐藏中的 get/set 绑定在一起.但是,当应用程序加载时,由于某种原因,它不会更新.出于好奇,我将其简化为基础,如下所示:

I have a project, where I bind a checkbox's IsChecked property with a get/set in the codebehind. However, when the application loads, it doesn't update, for some reason. Intrigued, I stripped it down to its basics, like this:

//using statements
namespace NS
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _test;
        public bool Test
        {
            get { Console.WriteLine("Accessed!"); return _test; }
            set { Console.WriteLine("Changed!"); _test = value; }
        }
        public MainWindow()
        {
            InitializeComponent();
            Test = true;
        }
    }
}

XAML:

<Window x:Class="TheTestingProject_WPF_.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
    <Viewbox>
        <CheckBox IsChecked="{Binding Path=Test, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </Viewbox>
</Grid>

而且,瞧,当我将它设置为 true 时,它​​没有更新!

And, lo and behold, when I set it to true, it did not update!

任何人都可以提出解决方案,或解释原因?

Anyone can come up with a fix, or explain why?

谢谢,不胜感激.

推荐答案

为了支持数据绑定,你的数据对象必须实现 INotifyPropertyChanged

In order to support data binding, your data object must implement INotifyPropertyChanged

此外,从演示文稿中分离数据总是一个好主意

public class ViewModel: INotifyPropertyChanged
{
    private bool _test;
    public bool Test
    {  get { return _test; }
       set
       {
           _test = value;
           NotifyPropertyChanged("Test");
       }
    }

    public PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
         if (PropertyChanged != null)
             PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

<Window x:Class="TheTestingProject_WPF_.MainWindow"
    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>
    <Viewbox>
        <CheckBox IsChecked="{Binding Path=Test, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </Viewbox>
</Grid>

背后的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel{Test = true};
    }
}

这篇关于WPF 数据绑定没有更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆