c# - WPF DataBinding 没有更新?

标签 c# wpf data-binding

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

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

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

谢谢,不胜感激。

最佳答案

为了支持数据绑定(bind),你的数据对象必须实现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};
    }
}

关于c# - WPF DataBinding 没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14965796/

相关文章:

c# - 在 wpf c# 中单击更改按钮图像

c# - 在 MVVM 模式中,推荐的实例化顺序是什么?

c# - 立方体的 WPF 纹理映射

javascript - 如何获取点击列表项的上下文以在 Nativescript 中的另一个页面中显示详细信息

c# - 在 Winforms C# 中调试数据绑定(bind)?

javascript - 如何呈现数据属性?

c# - 是否可以使用 Windows API 代码包设置/编辑文件扩展属性?

c# - 如何在 Entity Framework 5 代码中映射标识关系第一个子实体与多个互斥父实体

c# - 枚举列表 <Object> (Id, Name)

c# - 如何用额外的数据启动一个进程,然后搜索这个进程?