WPF为Dictionary提升属性更改事件

时间:2016-05-17 14:21:29

标签: c# wpf xaml mvvm

在WPF应用程序中,我使用的是MVVM Light和Fody。在我的View模型中,我有一个字典public Dictionary<string, string> OtherParticipants { get; set; }。在我的XAML中有一行:

<ListBox Height="350" HorizontalAlignment="Right" Margin="0,0,50,15"
Name="participantsListBox" VerticalAlignment="Center" 
Width="170" SelectionMode="Single" 
ItemsSource="{Binding OtherParticipants}" 
SelectedItem="{Binding SelectedParticipant}" DisplayMemberPath="Value"/>

在我的View模型中,我调用了一个方法:

private void NewMessagesReceivedHandler(Dictionary<string, List<BaseMessageDto>> result)
{
    var targetItems = OtherParticipants.Where(p => result.Keys.Any(n => p.Key == n)).ToList();

    var dialogueTarget = SelectedParticipant.Value;

    var dictItem = OtherParticipants.FirstOrDefault(i => i.Value == dialogueTarget);

    if (targetItems.Contains(dictItem))
    {
        //there is an open dialogue with this user
        //Dialogue.AddRange(result[dialogueTarget]);
        result[dialogueTarget].ForEach(m => Dialogue.Add(m));
        targetItems.Remove(dictItem);
    }

    for (int i = 0; i < targetItems.Count(); i++)
    {
        var participantKey = targetItems[i].Key;
        var participantNameWithNum = targetItems[i].Value;
        var incomingMessagesCount = result[participantKey].Count;

        if (_usernameWithNotificationsCountRegex.IsMatch(participantNameWithNum))
        {
            var matches = _usernameWithNotificationsCountRegex.Matches(participantNameWithNum)[0];
            var realUser = matches.Groups[1].Value;
            var currentMessagesCount = Convert.ToInt32(matches.Groups[3].Value);
            var total = currentMessagesCount + incomingMessagesCount;

            OtherParticipants[participantKey] = realUser + " (" + total + ")";
        }

        else
        {
            OtherParticipants[participantKey] = participantNameWithNum + " (" + incomingMessagesCount + ")";
        }
    }
}

Method主体并不真正相关,其背后的想法确实会改变OtherParticipants字典的内容。问题是这个更改没有反映在我的ListBox中。欢迎任何想法。
附注:我正在使用Fody,因此我的所有VM都标有[ImplementPropertyChanged]属性 编辑:评论中链接的ObservableDictionary的当前实现不起作用

1 个答案:

答案 0 :(得分:0)

字典实现可能需要使用Binding.IndexerName作为其属性名称来引发属性更改事件。