繁体   English   中英

将图像绑定到ComboBox.ItemTemplate

[英]Binding Image to ComboBox.ItemTemplate

我正在尝试我认为是一些相当简单的绑定。 我正在将字符对象集合绑定到我的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);
    }

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM