将图像绑定到ComboBox.ItemTemplate

时间:2014-08-26 03:05:31

标签: c# image data-binding combobox imagesource

我试图尝试一些相当简单的绑定。我将一个字符对象集合绑定到我的ComboBox。要显示组合框中的字符列表,请使用combobox.itemtemplate显示字符名称,级别和图像。

我可以显示角色名称和等级,但不能显示图像。我相信我正确地将图像绑定到xaml。知道我错过了什么吗?

XAML

    <ComboBox x:Name="Character_ComboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="328" Height="25">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Width="50" Text="{Binding Name}"/>
                        <TextBlock Width="50" Text="{Binding Level}"/>
                        <Image Source="{Binding dependaImage}"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

MainWindow.cs

    public ObservableCollection<Character> squad_members = new ObservableCollection<Character>();
    public Image depImage;
    public Image dependaImage 
    {
        get 
        {
            Image designate = new Image();
            BitmapImage bmi = new BitmapImage(new Uri("character1.png", UriKind.Relative));
            designate.Source = bmi;

            return designate;
        } 
    }

    public MainWindow()
    {
        InitializeComponent();

        squad_members.Add(new Character() { Name = "Wacken", Level = 8, Character_Class = CharacterClass.Mage, _Gender = Gender.Male, Strength = 6, Intelligence = 9, Dexterity = 3, Gold = 1255, Inventory = new ObservableCollection<Item>() { new Item("Gerrund Wand", "Magical Direction", 656, "Witcher Magical Wand", true ), new Item("Velcro Whip", "Whips your face off", 12, "Annoying as hell", true ), new Item("Invisibility Cloak", "Invisibility", 900, "Cloak of Invisibility", true)}});
        squad_members.Add(new Character() { Name = "Vrigun", Level = 4, Character_Class = CharacterClass.Mage, _Gender = Gender.Female, Strength = 3, Intelligence = 10, Dexterity = 1, Gold = 2055, Inventory = new ObservableCollection<Item>() { new Item("Satanic Girdings", "Demonic Protection", 6660, "Clothing protects user from attack", true ), new Item("Viper Staff", "Poisons Enemy Resolve", 860, "Bites and Kills Everything", true ), new Item("Baal Mask", "Infects enemy mind", 6660, "Possesses User's Opponents", false ) }});

        Binding comboBinding = new Binding();
        comboBinding.Source = squad_members;
        BindingOperations.SetBinding(Character_ComboBox, ComboBox.ItemsSourceProperty, comboBinding);
    }

1 个答案:

答案 0 :(得分:1)

您正在将Source属性绑定到Image ..试试这个

public ImageSource depImage;
public ImageSource dependaImage 
{
    get 
    {
        if( depImage == null )
            {
                depImage= new BitmapImage( new Uri( "character1.png", UriKind.Relative ) );
            }
            return depImage;
    } 
}

而且,您的Character类应具有此属性。