添加Item时,通过Converter绑定CollectionViewSource不会触发Converter

时间:2013-10-03 10:48:51

标签: c# wpf binding solid-principles

我需要在textblock中显示CollectionViewSource中不属于某种类型的元素数量。我试图通过在TextBlock的Text属性和Collection之间添加一个Converter来实现这一点,但是当我将项添加到绑定到CollectionViewSource的ObservableCollection时,不会触发Converter。集合确实发生了变化,因为如果我直接绑定到Count属性,这将触发转换器。

这是CollectionViewSource:

<CollectionViewSource x:Key="PatientRelatedWorkflowsCollection"
                              Source="{Binding PatientRelatedWorkflows}"
                              x:Uid="68cbfcf5481c43bdb83d6b31fe8ddc34">
            <CollectionViewSource.SortDescriptions>
                <my:SortDescription PropertyName="Patient.LastName" x:Uid="cf8cdd34c5d14c049a27e46848aca60d" />
            </CollectionViewSource.SortDescriptions>
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="Patient"
                                          Converter="{StaticResource WorkflowPatientGroupConverter}"
                                          x:Uid="d03e9b90df654454b5f5f7a8ee9cb1bf">
                </PropertyGroupDescription>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>

这是绑定:

<TextBlock Text="{Binding Converter={StaticResource CountNonConsultationWorkflowsConverter}}" />

这是转换器:

public class CountNonConsultationWorkflowsConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var workflowItems = value as ReadOnlyObservableCollection<Object>;
        if (workflowItems != null)
        {
            return workflowItems.Count(item => (item as WorkflowDataViewModel) != null && (item as WorkflowDataViewModel).WorkflowType != WorkflowType.ConsultPatient).ToString(CultureInfo.InvariantCulture);
        }
        return "0";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

注意:我设法通过将MultiBinding与MultiValueConverter一起使用,如下所示。这个工作,因为“Count”属性确实触发了PropertyChange,但我觉得这有点像黑客,并希望有一个更好的解决方案。

   <TextBlock.Text>
                <MultiBinding Converter="{StaticResource CountNonConsultationWorkflowsConverter}">
                    <Binding x:Uid="eb26d2c0bdb94d18ab48d8e25ce5f5ea" />
                    <Binding Path="Count" x:Uid="5555c981fda94bc6ad823c2f1e94b0f1" />
                </MultiBinding>
            </TextBlock.Text>

有关如何更好地做到这一点的任何想法?我感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以将UpdateSourceTrigger设置为Explicit,并在每次添加项目时更新它。