【问题标题】:Binding property only gets updated in code but not in the UI绑定属性仅在代码中更新,而不在 UI 中更新
【发布时间】:2021-01-10 21:03:41
【问题描述】:

背景:在我看来,我有一个TextBlock 和一个TextBox。一旦 TextBox 中的文本发生更改,TextChanged 事件就会被触发,并且在过滤列表后,我想更新绑定到 TextBlock 的属性。
在我的例子中,它是一个显示当前列表中联系人数量的计数器。

问题:当我调试时,属性 (ContactsCount) 总是会正确更新,但仅在代码中而不是在 UI 中。奇怪的是,UI 仅在我从 TextBox 中删除文本后更新到最后一个列表计数,而不是实际的。

代码
查看:

    <TextBlock Text="{Binding ContactsCount, UpdateSourceTrigger=PropertyChanged}"
               d:Text="4 Contacts"/>
    <xctk:WatermarkTextBox Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                           Watermark="Search Contact"
                           Margin="20,10">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <i:InvokeCommandAction Command="{Binding Path=SearchBoxTextChanged}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </xctk:WatermarkTextBox>

视图模型:

public string ContactsCount
{
    get => contactsCount;
    set
    {
        contactsCount = value;
        OnPropertyChanged(ContactsCount);
    }
}

public string SearchText
{
    get => searchText;
    set
    {
        searchText = value;
        OnPropertyChanged(SearchText);
    }
}

public CommandHandler SearchBoxTextChanged { get; set; }
SearchBoxTextChanged = new CommandHandler(TextChanged);

private void TextChanged()
{
     var filteredList = contactsList.Where(c => c.FirstName != null && c.FirstName.Contains(searchText.ToLower(), StringComparison.OrdinalIgnoreCase) || 
                                                       c.SecondName != null && c.SecondName.Contains(searchText.ToLower(), StringComparison.OrdinalIgnoreCase));
     Contacts = new ObservableCollection<Contact>(filteredList);
     // Bug: Doesn't update the UI after ContactsCount gets changed
     ContactsCount = $"{Contacts.Count} Contacts";
}

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    您没有发布 OnPropertyChanged() 方法的代码,但我怀疑是否应该发布

    OnPropertyChanged("SearchText");
    

    或更好

    OnPropertyChanged(nameof(SearchText));
    

    即传入更新属性的名称,而不是其值。

    【讨论】:

    • 那不是真的——我真的犯了一个愚蠢的错误。无论如何你是完全正确的。就我而言,我什至不需要写属性名称,可以将参数留空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    相关资源
    最近更新 更多