c# - 在 ComboBox 的选中项中显示图像

标签 c# wpf xaml combobox datatemplate

我有一个用于我的 WPF 窗口 ComboBox 的自定义模板,它显示继承自 ComboBoxItem 的项,这些项也具有 Image 属性(以便我的项可以显示文本和图像)。对于任何给定项目,文本和图像都按预期显示在 ComboBox 的弹出菜单中,但我无法在当前选定的项目中显示图像。

显示当前选定项的 ComboBox 模板中的 ContentPresenter 将其 Content 属性正确绑定(bind)到 {TemplateBinding SelectionBoxItem},并且其 ContentTemplate 绑定(bind)到以下静态资源:

    <DataTemplate x:Key="SelectionBoxItemTemplateTextAndImage" DataType="{x:Type SB:SBComboBoxItem}">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="20"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Image Source="{Binding Image}"/>
            <TextBlock Grid.Column="1" Text="{Binding}"/>
        </Grid>
    </DataTemplate>

SBComboBoxItem 是继承自 ComboBox 的自定义控件,包含正确注册为 DependencyProperty 的“Image”属性。

我已经尝试过该 DataTemplate 的替代实现,包括使用:

{Binding Path=Image, RelativeSource={RelativeSource TemplatedParent}}

作为图像的来源。这没有用,即使当我将 TextBlock 的 Text 属性设置为时文本仍然显示:

{Binding Path=Content, RelativeSource={RelativeSource TemplatedParent}}

我试过并发现了许多显示文本的实现,但对等的实现对图像不起作用。我不明白为什么这不起作用,因为设置弹出窗口以显示图像和文本是一件轻而易举的事。

编辑:这是为 ComboBoxItem 添加的处理图像的功能,以防我在那里做错了什么:

    public static readonly DependencyProperty ImageProperty = DependencyProperty.Register("Image", typeof(Image), typeof(SBComboBoxItem));
    public Image Image { get { return (Image)GetValue(ImageProperty); } set { SetValue(ImageProperty, value); } }

这里是我添加了项目的组合框:

<ComboBox SelectedIndex="1">
    <SB:SBComboBoxItem Content="Text">
        <SB:SBComboBoxItem.Image>
            <Image Source="..\Images\Table.png"/>
        </SB:SBComboBoxItem.Image>
    </SB:SBComboBoxItem>
    <SB:SBComboBoxItem Content="MoreText">
        <SB:SBComboBoxItem.Image>
            <Image Source="..\Images\Euclidian.png"/>
        </SB:SBComboBoxItem.Image>
    </SB:SBComboBoxItem>
</ComboBox>

最佳答案

尽管我使用 DataTemplate 通过 DataTemplate 的 DataType 属性公开所选组合框项的基础类型,但我的 ComboBox 的 SelectionBoxItem 属性显然返回了一些无法转换为我的自定义 ComboBoxItem 的内容。我不知道这是为什么,也不知道为什么它没有触发任何运行时错误,但我发现通过绑定(bind)到 ComboBox 的 SelectedItem 属性而不是 ContentPresenter 中的 SelectionBoxItem 允许我访问用户定义的属性。

关于c# - 在 ComboBox 的选中项中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11603081/

相关文章:

c# - 从 WPF UserControl 访问 ResourceDictionary

c# - 如何格式化 Visual Studio 2012 中的所有文件?

c# - EF Code First 6.1 将 ID 从 Int 更改为 Long

c# - MV4 路由 来自 MySQL 数据库的动态路由

.net - WCF 服务 TCP/Ip 与 Http 协议(protocol)的 Internet 与 Intranet 服务消耗

c# - 如何从另一个应用程序打开 WPF 窗口

wpf - 公共(public)与私有(private)附加属性

c# - WPF Textblock TargetNullValue 不工作?

windows - 在 Windows 8 (Metro) 应用程序中获取 XAML 控件的 hWnd?

c# - 如何区分 .net WebBrowser 组件和实际浏览器?