WPF DataBinding not updating?

后端 未结 1 1323
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 22:12

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. I

相关标签:
1条回答
  • 2020-11-27 22:54

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

    Also, it's always a good idea to 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>
    

    Code Behind:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new ViewModel{Test = true};
        }
    }
    
    0 讨论(0)
提交回复
热议问题