【问题标题】:How to bind dictionary with bitmap to combobox如何将带有位图的字典绑定到组合框
【发布时间】:2016-01-29 11:33:00
【问题描述】:

我在将Dictionary<string, Bitmap> 绑定到我的combobox 时遇到问题。 Bitmaps 保存在资源文件中。

这可以加载组合框中的项目:

ComboBoxLanguage.ItemsSource = Languages;
ComboBoxLanguage.DisplayMemberPath = "Value";
ComboBoxLanguage.SelectedValuePath = "Key";
ComboBoxLanguage.SelectedValue = Settings.Default.language;

这是我的字典:

Languages = new Dictionary<string, Bitmap>
{
    { "en-US", Properties.Resources.US},
    {"de-DE", Properties.Resources.DE}
};

但我的ComboBox 只显示Sysytem.Drawing.Bitmap

有人可以帮帮我吗?

【问题讨论】:

  • 您应该在 WPF 中为位图使用 BitmapSource(而不是 WinForms 的 Bitmap)。然后,您必须将 ComboBox 的 ItemTemplate 设置为带有 Image 控件的 DataTemplate,该控件使用 Value 属性作为其 Source

标签: c# wpf dictionary combobox bitmap


【解决方案1】:

可能您需要使用ObservableCollection 并制作包装类。

public class ComboBoxData
{
    public string Path { get; set; }
    public string Text { get; set; }
}

在视图模型中,您应该指定一个组合框元素列表。

public ObservableCollection<ComboBoxData> Languages { get; set; }
public View()
    {
        InitializeComponent();

        this.Languages = new ObservableCollection<ComboBoxData>()
                          {
                              new MyComboboxData(){Path = "Image1.jpg", Text = "Text1"},
                              new MyComboboxData(){Path = "Image2.jpg", Text = "Text2"}
                          };

        this.DataContext = this;
}

并在 xaml 中将您的组合框绑定到此集合。

<ComboBox Name="ComboBoxLanguage" ItemsSource="{Binding Languages}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="{Binding Path}"/>
                    <TextBlock Text="{Binding Text}"/>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
</ComboBox>

【讨论】:

    猜你喜欢
    • 2018-12-26
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多