正在将图像绑定到ComboBox.ItemTemplate

本文关键字:ComboBox ItemTemplate 绑定 图像 | 更新日期: 2023-09-27 18:19:33

我正在尝试一些我认为相当简单的绑定。我正在将角色对象集合绑定到我的组合框。要在组合框中显示字符列表,我使用组合框项模板,在其中显示字符"名称"、"级别"answers"图像"。

我可以显示角色名称和级别,但不能显示图像。我相信我将图像正确地绑定到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>

主窗口.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);
    }

正在将图像绑定到ComboBox.ItemTemplate

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

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

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