我将 PrintQueue
的 PageMediaSize
集合绑定(bind)到 ComboBox
的 ItemSource
(这有效美好的)。然后,我将 ComboBox
的 SelectedItem
绑定(bind)到 PrintQueue
的 DefaultPrintTicket.PageMediaSize
。虽然这会将选定值设置为 DefaultPrintTicket.PageMediaSize
就好了,但它不会将 ComboBox
的初始选定值设置为 DefaultPrintTicket.PageMediaSize 的初始值
这是因为 DefaultPrintTicket.PageMediaSize
引用与集合中的任何引用都不匹配。但是我不希望它通过引用来比较对象,而是通过值来比较对象,但是 PageMediaSize
不会覆盖 Equals(我无法控制它)。我真正想做的是为要使用的 ComboBox
设置一个 IComparable
,但我看不到有任何方法可以做到这一点。我尝试过使用 Converter
,但我需要的不仅仅是值,而且我不知道如何将集合传递给 ConverterProperty
。关于如何处理这个问题的任何想法。
这是我的xaml
<ComboBox x:Name="PaperSizeComboBox"
ItemsSource="{Binding ElementName=PrintersComboBox, Path=SelectedItem,
Converter={StaticResource printQueueToPageSizesConverter}}"
SelectedItem="{Binding ElementName=PrintersComboBox,
Path=SelectedItem.DefaultPrintTicket.PageMediaSize}"
DisplayMemberPath="PageMediaSizeName"
Height="22"
Margin="120,76,15,0"
VerticalAlignment="Top"/>
以及获取 PageMediaSize
集合的转换器代码
public class PrintQueueToPageSizesConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return value == null ? null :
((PrintQueue)value).GetPrintCapabilities().PageMediaSizeCapability;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
编辑
我尝试将 DefaultPrintTicket.PageMediaSize
设置为 InitializeComponent
之前集合中的相应引用,但这没有用。当我从 ComboBox
中选择某些内容时,它肯定会设置值,但它似乎并没有相反。
最佳答案
是否可以为 PageMediaSize
创建一个包装类并覆盖该包装类中的 Equals(object)
方法?然后您可以将此包装类的实例添加到您的集合中,这样它们就不再通过引用进行比较。当然,您将需要一些代码来包装和解包您的 PageMediaSize
实例,但这是我能想到的最佳方式。
关于c# - 当引用不在 ItemsSource 中时 WPF 绑定(bind)到 ComboBox SelectedItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2969134/