动态绑定未更新

时间:2014-08-07 06:13:12

标签: c# wpf xaml

我是wpf的初学者。我正在按照一本教科书来学习,但是每当我编写动态绑定部分时,即使在严格按照每个指令执行三次之后,它也会显示出来。 这是背后的代码

using System;
using System.ComponentModel;


namespace KarliCards_GUI
{
    [Serializable]
    public class GameOptions:INotifyPropertyChanged
    {
        private bool _playAgainstComputer = false;
        public bool PlayAgainstComputer 
        { 
            get
            {
                return _playAgainstComputer;

            }
        set
        {
            _playAgainstComputer = value;
            OnPropertyChanged("PlayAgainstComputer");
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

}

}

在XAML文件中,我想通过使用DataContext动态绑定复选框的IsChecked属性,DataContext将有一个GameOptions实例。 下面的部分代码在XAML文件中

<CheckBox Content="Play against computer" HorizontalAlignment="Left" Margin="11,33,0,0" VerticalAlignment="Top" Name="playAgainstComputerCheck" IsChecked="{Binding Path=PlayAgainstComputer}" />

及以下是该XAML的csharp文件的代码

namespace KarliCards_GUI
{
    public partial class Options : Window
    {
        private GameOptions _gameOptions;
        public Options()
        {
            if (_gameOptions == null)
            {
                if (File.Exists("GameOptions.xml"))
                {
                    using (var stream = File.OpenRead("GameOptions.xml"))
                    {
                        var serializer = new XmlSerializer(typeof(GameOptions));
                        _gameOptions = serializer.Deserialize(stream) as GameOptions;
                    }
                }
                else
                    _gameOptions = new GameOptions();
            }
            DataContext = _gameOptions;
            InitializeComponent();
        }
   }
}

我面临的问题是,在属性&#39; PlayAgainstComputer&#39;中,如果我将变量(_playAgainstComputer)设置为&#39; value&#39;它总是在复选框中选中。

1 个答案:

答案 0 :(得分:0)

自设置InitializeComponent()后调用DataContext方法以来可能就是这种情况。

IsChecked CheckBox属性的默认值为true。我建议先调用InitializeComponent()方法,然后设置DataContext。