ComboBox.ItemTemplate 未正确显示选择

2024-05-14

在问题中c# wpf - 无法同时设置 DisplayMemberPath 和 ItemTemplate https://stackoverflow.com/questions/18273415/c-sharp-wpf-cannot-set-both-displaymemberpath-and-itemtemplate,我读到您可以替换 DisplayMemberPath 以在 ComboBox 中组合多个数据项。

我使用 ItemTemplate 设置了组合框,并且已成功填充。但是,当我在组合框中选择一个项目时,我会显示 Data.MaterialNumber,而不是我选择的实际文本。

MaterialNumbers 是一个 ObservableCollection

有人可以告诉我为什么我的 ComboBox 在选择项目后无法正确显示该项目吗?

// Binding from my ViewModel, which retrieves material numbers correctly.
ObservableCollection<MaterialNumber> MaterialNumbers = GetMaterialNumbers();

<ComboBox Grid.Row="0" Grid.Column="1" ItemsSource="{Binding MaterialNumbers}"
    SelectedItem="{Binding MaterialNumber}"
    Validation.Error="View_Validator" Validation.ErrorTemplate="{StaticResource ErrorTemplateBorder}"
    IsEnabled="{Binding IsEnabled}" IsEditable="True" IsReadOnly="True" Margin="0,10,0,0">
    <ComboBox.ItemTemplate>
    <DataTemplate>
        <TextBlock>
            <TextBlock.Text>
            <MultiBinding StringFormat="{}{0}: {1}">
                <Binding Path="Program.Name" />
                <Binding Path="MaterialNumberString" />
                <Binding UpdateSourceTrigger="PropertyChanged" />
                <Binding NotifyOnValidationError="True" />
                <Binding ValidatesOnDataErrors="True" />
            </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

感谢这篇文章http://www.shujaat.net/2010/08/wpf-editable-combobox-with-datatemplate.html http://www.shujaat.net/2010/08/wpf-editable-combobox-with-datatemplate.html,我能够弄清楚为什么在选择某个项目时我的 ComboBox 没有正确显示。这是因为我的 ComboBox 设置为 IsEditable="True"。显然,当使用 ComboBox.ItemTemplate 并设置 MultiBinding 时,ComboBox 无法确定要显示哪个项目,因此它会显示类。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ComboBox.ItemTemplate 未正确显示选择 的相关文章

随机推荐