【问题标题】:Wrapped image not displaying in combo box组合框中不显示包裹的图像
【发布时间】:2012-12-18 15:27:10
【问题描述】:

我使用以下问题中描述的方法来填充组合框。

ComboBox ItemTemplate does not support values of type 'Image'

ComboBox 填充有包含图像和一些数据的包装类的实例。但是,正如该问题的发布者所说,图像不会显示在组合框中,但是选择其中一个空白条目确实可以正确绑定数据。

数据绑定在模型视图中,因为它与外部数据源交互,但是图像是特定于 UI 的,因此绑定在用户控件的代码中。

如何让图片显示?

代码:

public ObservableCollection<Wrapper> Images { get; set; }
public Class Wrapper
{
    public Wrapper(int data,  Image img)
    {
            Data = data;
            Img = img;              
    }
    public int Data { get; set; }
    public Image Img { get; set; }

}

int selectedData;

public int SelectedData
{
    get { return selectedData; }
    set
        {
            selectedData = value;
            (this.Resources["model"] as MyModel).External = Images[selectedData].Data;
            SendPropertyChanged("SelectedData");
        }
 }

xaml:

<ComboBox ItemsSource="{Binding Images}" SelectedIndex="{Binding SelectedData}">
     <ComboBox.ItemTemplate>
         <DataTemplate>
             <Image Source="{Binding Img}" Height="83" Width="71"/>
         </DataTemplate>
     </ComboBox.ItemTemplate>
</ComboBox>

【问题讨论】:

    标签: wpf image binding combobox


    【解决方案1】:

    Image 控件的Source 不能是另一个Image 控件。将Img 属性的类型更改为ImageSource

    public class Wrapper
    {
        ...
        public ImageSource Img { get; set; }
    }
    

    【讨论】:

    • 您也可以使用string 并给出图像的路径。要创建ImageSource,您可以使用BitmapImage 类。
    • 我正在使用 BitmapFrame 创建一个图像源并将其分配给绑定图像。将绑定属性设置为您所描述的源就像一个魅力。
    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2021-03-22
    • 2011-06-27
    • 2023-04-07
    相关资源
    最近更新 更多