WPF 数据绑定未更新?

2024-03-26

我有一个项目,我将复选框的 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 时,它​​没有更新!

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

谢谢,我们将不胜感激。


为了支持数据绑定,您的数据对象必须实现INotifyPropertyChanged http://wpftutorial.net/INotifyPropertyChanged.html

另外,这总是一个好主意将数据与表示分离 https://stackoverflow.com/questions/14381402/wpf-programming-methodology/14382137#14382137

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};
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF 数据绑定未更新? 的相关文章

随机推荐