【问题标题】:Dynamic Binding is not updating动态绑定未更新
【发布时间】:2014-08-07 06:13:11
【问题描述】:

我是 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 文件中,我想通过使用具有 GameOptions 实例的 DataContext 动态绑定复选框的 IsChecked 属性。 以下部分代码在 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();
        }
   }
}

我面临的问题是,在属性“PlayAgainstComputer”中,如果我将变量(_playAgainstComputer)设置为“值”,它总是在复选框中选中。

【问题讨论】:

  • 可能是这种情况,因为在设置 DataContext 之后调用了 InitializeComponent() 方法。 CheckBoxIsChecked 属性的默认值为 true。我建议先调用InitializeComponent()方法,然后设置DataContext
  • 提示:我们使用 nameof(PlayAgainstComputer) 而不是 OnPropertyChanged("PlayAgainstComputer"); 中的 "PlayAgainstComputer",如果你曾经重命名这个,字符串将不会被重命名。

标签: c# wpf xaml


【解决方案1】:

可能是因为在设置DataContext 之后调用了InitializeComponent() 方法。

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

【讨论】:

  • 可以把xml反序列化后的值贴出来吗?
  • Debug.WriteLine("BarunDEBUG_Result-> "+_gameOptions.PlayAgainstComputer);它在调试窗口中显示 true
  • _playAgainstComputer = value; 行上放置一个断点,然后在UI 上切换CheckBox。查看value 是否在true(选中)和false(未选中)之间变化。如果那行得通,那么我真的没有看到任何问题。
  • 此时 _playAgainstComputer=false 和 value=true 稍后在变量中分配以使其为真。这是我的问题,谁在设置属性为“真”,以及如何避免它进行动态绑定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多