2

我的 WPF 窗口中有这个组合框。

<ComboBox DisplayMemberPath="Description" SelectedValuePath="ID" ItemsSource="{Binding Source={StaticResource CvsPrinters}}" SelectedValue="{Binding CheckPrinterID}" />

我的问题是,在加载窗口时,SelectedValue 绑定导致我的源数据更改为 ItemsSource 中的第一项,而不是将 Combobox 的 SelectedValue 设置为 ItemsSource 中的适当项目。

CheckPrinterID 来自列表视图选择数据上下文,并且此问题仅发生在加载时在该列表视图中最初选择的项目上。当我在列表框中选择另一个项目时,组合框正确选择了正确的项目,一切都很好,但不幸的是我的初始项目已更新,现在不正确。

4

3 回答 3

1

我猜您正在尝试通过公共属性ListView进行同步。ComboBox尝试在 ListView 中将IsSynchronizedWithCurrentItem设置为 True,并确保在加载期间设置了SelectedItemSelectedIndexfor 。ListView

于 2011-07-12T18:01:11.977 回答
0

如果您在 DataContext 对象中有一定的灵活性,您可以尝试将选定的 CheckPrinter 属性更改为数据对象类型而不是 ID 并切换到使用 SelectedItem 而不是 SelectedValue(由于某种原因 SelectedValue 的行为不同,尤其是在初始加载时)和然后从代码中的该值中提取 ID。

如果出于某种原因不能在 DataContext 对象中使用 CheckPrinter 对象,您也可以在 UI 端使用 ID 列表作为 ItemsSource,然后再次使用 SelectedItem。要让列表在 ComboBoxItems 中显示您想要的内容,您需要使用 IValueConverter 根据 ID 提取描述值:

<ComboBox ItemsSource="{Binding Source={StaticResource CvsPrinterIds}}" SelectedItem="{Binding CheckPrinterID}" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock >
                <TextBlock.Text>
                    <Binding>
                        <Binding.Converter>
                            <local:MyDescriptionLookupConverter Printers="{StaticResource CvsPrinters}"/>
                        </Binding.Converter>
                    </Binding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

和一个简单的转换器来进行 ID-Description 查找(添加一些 null 和 cast 检查):

    public class MyDescriptionLookupConverter : IValueConverter
    {
        public IEnumerable<Printer> Printers { get; set; }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Printers.First(p => p.Id == (int)value).Description;
        }
        ...
    }
于 2011-07-13T00:27:40.763 回答
0

尝试在 DisplayMemberPath 之前重新排列 ItemsSource。

于 2011-07-12T18:54:32.903 回答