window 打开时 WPF 绑定不正确

WPF bindings not correct when window opens

我正在编写一个带有单个 window 的小型 WPF 实用程序,到目前为止代码如下。我正在使用 PostSharp 自动处理 属性 更改通知,并且当我 select 组合框中的不同组织时,绑定正在更新。但是,当 window 首次打开并且行

organisationComboBox.SelectedIndex = 0;

执行,绑定不更新。 organisationComboBox_SelectionChanged() 方法中设置的断点显示项目 selected 的 _lightningLocationsEnabled 变量设置为 true,并且依赖于它的属性设置正确,但控制属性绑定初始显示值,如果变量为 false,它们将显示这些值。

PostSharp 文档建议不需要手动强制 属性 更改通知,所以我认为我做错了什么。谁能帮我找出问题所在?

这是代码

using DynaMiX.Common.Groups.Constants;
using DynaMiX.Data.Operations;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using PostSharp.Patterns.Model;

namespace LightningMapLocationToolGUI
{
    [NotifyPropertyChanged]
    public partial class MainWindow : Window
    {
        private IOrganisationRepository _organisationRepository = new OrganisationRepository();
        private bool _lightningLocationsEnabled;

        public MainWindow()
        {
            InitializeComponent();
            BindOrganisations();
        }

        public string StatusText => $"Lightning Map Locations feature is { (_lightningLocationsEnabled ? "ENABLED" : "DISABLED") }";
        public Brush StatusColorBrush => new SolidColorBrush(_lightningLocationsEnabled ? Colors.Green : Colors.Red);
        public string EnableButtonText => _lightningLocationsEnabled ? "Disable" : "Enable";

        private void BindOrganisations()
        {
            var orgList = _organisationRepository
                .GetOrganisationSummaries()
                .Where(o => o.DatabaseState == DatabaseState.Active)
                .OrderBy(o => o.Name)
                .ToList();

            organisationComboBox.ItemsSource = orgList;
            organisationComboBox.DisplayMemberPath = "Name";
            organisationComboBox.SelectedValuePath = "OrganisationId";
            organisationComboBox.SelectedIndex = 0;
        }

        private void organisationComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _lightningLocationsEnabled = _organisationRepository.LightningLocationsEnabledFor((long)organisationComboBox.SelectedValue);
        }
    }
}

这里是绑定控件的XAML

<Label x:Name="statusLabel" Content="{Binding StatusText}" TextBlock.Foreground="{Binding StatusColorBrush}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="25,71,0,0"/>
<Button x:Name="enableButton" Content="{Binding EnableButtonText}" Visibility="{Binding ControlVisibility}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="309,74,0,0"/>

将 BindOrganisations 放入 Window 的 Loaded 事件中。

不要忘记可以多次调用 Loaded 事件,您可以使用布尔标志。