WPF数据绑定未更新?

21

我有一个项目,在其中将复选框的IsChecked属性与代码后台中的get/set绑定。但是,当应用程序加载时,由于某种原因它不会更新。我很好奇,所以我将其简化为如下形式:

//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时,它并没有更新!

有人能想出一个解决办法或解释一下吗?

谢谢,感激不尽。


4
我认为我不应该因为阅读了另一个来源而遭到负投票的惩罚,因为这并不是在MSDN上学到的内容。 - It'sNotALie.
3
我没有点踩,但我怀疑这个问题是因为缺乏求知精神而被踩的。这个问题非常基础,任何使用WPF绑定系统的人都知道需要实现INotifyPropertyChanged来使属性在改变时通知UI重新评估绑定。几乎每一个介绍WPF绑定的教程都涵盖了这个概念。 - Rachel
16
这就好像说新手因为不知道如何使用基本方法而应该被踩。 这是由于缺乏知识。 WPF 对我来说相当新。 - It'sNotALie.
3
@ofstream 这个踩并不是因为你缺乏知识,而是因为你没有付出足够的研究努力。 - Rachel
1
你也可以说,新手因为缺乏研究努力而应该被降低评分。 MSDN + MSDN 博客可能已经回答了这里发布的大约 25% 的所有问题。 - It'sNotALie.
显示剩余3条评论
1个回答

36
为了支持数据绑定,你的数据对象必须实现 INotifyPropertyChanged 接口。
同时,将Separate Data from Presentation(将数据与呈现分离)始终都是一个好主意。
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};
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接