如果您在 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;
}
...
}