使用DataTemplate在ComboBox中绑定图像

时间:2013-02-28 10:52:34

标签: wpf xaml .net-4.0 combobox datatemplate

我正在处理现有代码。这个东西有一个带有几个ComboBoxItems的ComboBox。每个项目都有一个StackPanel,其中有一个Image控件和一个TextBlock。

现在,Image控件的source属性设置为存储在XAML文件中的不同矢量图像,而TextBlock的Text属性设置为本地化字符串。

我想通过使用单独的ComboBoxItem但使用DataTemplate来实现它。我可以为TextBlock创建一个字符串列表,但我无法弄清楚如何将图像绑定到相应的图像控件。

我对任何其他更好的解决方案持开放态度。此外,如果您认为正确的方法是现有的,请告诉我。

这可能是一个重复的问题,但我找不到适合我的问题的问题。 如果是,则指向其他问题的链接就足够了。

编辑:已添加代码

<ComboBox x:Name="imageInfoLevelsComboBox" SelectedIndex="1" 
          Style="{DynamicResource ComboBoxToolBarStyle}" 
          Margin="6,6,6,0" Width="50" 
          ToolTip="{x:Static Viewing:ViewingTexts.ImageInformationLevels}" 
          SelectionChanged="OnImageInfoLevelsComboBoxSelectionChanged" >
    <ComboBoxItem x:Name="showAllComboBoxItem" 
                  Style="{DynamicResource ComboBoxItemToolBarStyle}">
        <StackPanel Orientation="Horizontal">
            <Image x:Name="ImageInfoAllImage" 
                   Source="{StaticResource ImageInfoFullIcon}" 
                   Margin="0,0,4,0" 
                   Width="24" Height="24"/>
            <TextBlock 
                Text="{x:Static Viewing:ViewingTexts.ImageInformationFull}"
                Margin="10,0,0,0" 
                VerticalAlignment="Center"/>
        </StackPanel>
    </ComboBoxItem>
    <ComboBoxItem x:Name="showImportantComboBoxItem" 
        Style="{DynamicResource ComboBoxItemToolBarStyle}">
        <StackPanel Orientation="Horizontal">
            <Image x:Name="ImageInfoImportantImage" 
                   Source="{StaticResource ImageInfoLimitedIcon}" 
                   Margin="0,0,4,0" 
                   Width="24" Height="24"/>
            <TextBlock 
                Text="{x:Static Viewing:ViewingTexts.ImageInformationIntermediate}"
                       Margin="10,0,0,0" 
                       VerticalAlignment="Center"/>
        </StackPanel>
    </ComboBoxItem>
    <ComboBoxItem x:Name="showNotificationsComboBoxItem" 
        Style="{DynamicResource ComboBoxItemToolBarStyle}">
        <StackPanel Orientation="Horizontal">
            <Image x:Name="ImageInfoNotificationsImage" 
                Source="{StaticResource ImageInfoNoneIcon}" 
                Margin="0,0,4,0" Width="24" Height="24"/>
            <TextBlock Text="{x:Static Viewing:ViewingTexts.ImageInformationNone}"
                       Margin="10,0,0,0" VerticalAlignment="Center"/>
        </StackPanel>
    </ComboBoxItem>
</ComboBox>

我认为我能做的是创建一个包含2个对象的类,一个是字符串类型,另一个是Image。然后创建一个列表并将其与组合框绑定,但问题是我不确定如何将矢量图像用作对象。

感谢。

2 个答案:

答案 0 :(得分:1)

我认为你需要绑定一个至少有两个属性的对象列表,而不仅仅是一个字符串列表。一个属性将包含文本块的字符串,另一个属性将是图像的urisource。

有关urisource定义Wpf - relative image source path

的示例,请参阅此链接

答案 1 :(得分:1)

将ComboBox的ItemsSource绑定到具有表示文本和图像的属性的对象集合。然后,您需要创建一个IValueConverter并在图像的绑定上指定它的实例,该实例可以将对象上的属性值转换为图像源。

这是一个例子: http://www.codewrecks.com/blog/index.php/2010/07/23/bind-an-image-to-a-property-in-wpf/