c# - 当引用不在 ItemsSource 中时 WPF 绑定(bind)到 ComboBox SelectedItem

标签 c# wpf binding combobox

我将 PrintQueuePageMediaSize 集合绑定(bind)到 ComboBoxItemSource(这有效美好的)。然后,我将 ComboBoxSelectedItem 绑定(bind)到 PrintQueueDefaultPrintTicket.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/

相关文章:

c# - 如何在触发后删除事件处理程序?

c# - Protobuf-net 和泛型

c# - 验证在单元测试中失败

C#/WPF 应用程序抛出 ObjectDisposedException;为什么我无法捕获或获取堆栈跟踪?

wpf - Entity Framework 4.0 数据绑定(bind)与排序不起作用

c# - WPF中不同窗口之间的数据共享

javascript - 使用闭包/函数绑定(bind)将 self 函数作为回调传递

c# - HttpWebRequest.GetResponse() 返回 404 错误

c# - 绑定(bind)实际上是如何工作的?

javascript - ionic 计时器绑定(bind)不起作用