В этом файле класса ItemsProcessing.cs есть проблема, сделай изменение картинки как в…
- User
В этом файле класса ItemsProcessing.cs есть проблема, сделай изменение картинки как в LevelComboBox_SelectedIndexChanged для чар тоже(Если в кратце нужно чтобы картинка менялась в зависимости не только от уровня, но и от чар) using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;
namespace Albion_Helper { public class ItemsProcessing { private ListView BrowserList; private ListView InventoryList; private ImageList ImageList; private ItemsList itemsList; private int levelColumnIndex = 3; private int enchantmentColumnIndex = 4;
public ItemsProcessing(ListView browserList, ListView inventoryList, ImageList imageList) { BrowserList = browserList; InventoryList = inventoryList; ImageList = imageList; itemsList = new ItemsList(); LoadImagesToImageList(); PopulateBrowseList(); InitializeListViewMouseHandlers(); } private void LoadImageToImageList(string imageFileName) { if (!ImageList.Images.ContainsKey(imageFileName)) { string imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BuyMenu", "ItemsIco", imageFileName + ".png"); if (File.Exists(imagePath)) { using (var bmpTemp = new Bitmap(imagePath)) { ImageList.Images.Add(imageFileName, new Bitmap(bmpTemp)); } } } } public void LoadImagesToImageList() { foreach (var item in itemsList.GetItems()) { // Получаем ImageFileName для текущего item string imageFileName = item.GetImageFileName(); LoadImageToImageList(imageFileName); } } public void PopulateBrowseList() { List<Item> items = GetSortedItems(); BrowserList.Items.Clear(); foreach (Item item in items) { ListViewItem listViewItem = CreateBrowserListViewItem(item); BrowserList.Items.Add(listViewItem); } } public ListViewItem CreateBrowserListViewItem(Item item) { ListViewItem listViewItem = new ListViewItem { ImageKey = item.GetImageFileName(), Tag = item }; listViewItem.SubItems.Add(item.EnglishName); listViewItem.SubItems.Add(item.GetLocalizedCategory()); return listViewItem; } public List<Item> GetSortedItems() { return itemsList.GetItems().OrderBy(item => item.EnglishName).ToList(); } public void InitializeListViewMouseHandlers() { BrowserList.MouseClick += (sender, e) => HandleMouseClick((ListView)sender, e); InventoryList.MouseClick += (sender, e) => HandleMouseClick((ListView)sender, e); } private void HandleMouseClick(ListView listView, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ListViewHitTestInfo hit = listView.HitTest(e.X, e.Y); if (hit.SubItem != null) { if (listView == InventoryList) { DisplayComboBoxOrTextBox(hit); } } } } public void AddToInventory() { if (BrowserList.SelectedItems.Count > 0) { foreach (ListViewItem item in BrowserList.SelectedItems) { Item selectedItem = (Item)item.Tag; ListViewItem newItem = CreateInventoryListViewItem(selectedItem); InventoryList.Items.Add(newItem); BrowserList.Items.Remove(item); } } } public void RemoveFromInventory() { if (InventoryList.SelectedItems.Count > 0) { foreach (ListViewItem item in InventoryList.SelectedItems) { Item selectedItem = (Item)item.Tag; ListViewItem newItem = CreateBrowserListViewItem(selectedItem); BrowserList.Items.Add(newItem); InventoryList.Items.Remove(item); } } } public ListViewItem CreateInventoryListViewItem(Item item) { ListViewItem listViewItem = new ListViewItem(); listViewItem.ImageKey = item.GetImageFileName(); listViewItem.SubItems.Add(item.GetFullEnglishName()); listViewItem.SubItems.Add("1"); listViewItem.SubItems.Add(item.Level.ToString()); listViewItem.SubItems.Add(item.Charms.ToString()); listViewItem.SubItems.Add(item.GetLocalizedCategory()); listViewItem.Tag = item; return listViewItem; } private void DisplayComboBoxOrTextBox(ListViewHitTestInfo hit) { int yOffset = 65; // Смещение по вертикали // Индексы столбцов (могут быть другими - настроить под свою структуру) int quantityColumnIndex = 2; // Индекс колонки для количества int levelColumnIndex = 3; // Индекс колонки для уровня int enchantmentColumnIndex = 4; // Индекс колонки для чаров // Проверяем, что клик был по интересующим нас колонкам в InventoryList int columnIndex = hit.Item.SubItems.IndexOf(hit.SubItem); if (columnIndex == quantityColumnIndex || columnIndex == levelColumnIndex || columnIndex == enchantmentColumnIndex) { // Определяем границы ячейки и контрол для отображения Rectangle cellBounds = hit.SubItem.Bounds; cellBounds.Offset(15, yOffset); cellBounds.Height -= yOffset; // Корректируем высоту с учетом смещения Control controlToDisplay = null; // Создание и настройка TextBox для количества if (columnIndex == quantityColumnIndex) { TextBox quantityTextBox = new TextBox { Bounds = cellBounds, Text = hit.SubItem.Text, Tag = hit.Item }; quantityTextBox.Leave += TextBox_Leave; hit.Item.ListView.Parent.Controls.Add(quantityTextBox); quantityTextBox.BringToFront(); quantityTextBox.Visible = true; quantityTextBox.Focus(); quantityTextBox.Leave += (sender, e) => quantityTextBox.Visible = false; quantityTextBox.KeyPress += (sender, e) => { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } }; quantityTextBox.KeyDown += (sender, e) => { if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) { hit.SubItem.Text = quantityTextBox.Text; quantityTextBox.Visible = false; } }; controlToDisplay = quantityTextBox; } else { // Создание и настройка ComboBox для уровня или чаров ComboBox comboBox = new ComboBox { Bounds = cellBounds, DropDownStyle = ComboBoxStyle.DropDownList, Tag = hit.Item // Добавляем ссылку на ListViewItem в Tag ComboBox’а }; comboBox.Name = columnIndex == levelColumnIndex ? "level" : "enchantment"; comboBox.Leave += (sender, e) => comboBox.Visible = false; comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged; // Наполнение ComboBox значениями, исходя из колонки if (columnIndex == levelColumnIndex) { int minLevel = (hit.Item.Tag as Item)?.MinLevel ?? 1; for (int i = minLevel; i <= 8; i++) { comboBox.Items.Add(i.ToString()); } comboBox.SelectedItem = hit.SubItem.Text; comboBox.SelectedIndexChanged += LevelComboBox_SelectedIndexChanged; } else if (columnIndex == enchantmentColumnIndex) { Item item = hit.Item.Tag as Item; // Необходимо зависеть от текущего уровня выбранного экипированного item int currentLevel = Convert.ToInt32(hit.Item.SubItems[levelColumnIndex].Text); if (currentLevel >= 4) { // Наполнение ComboBox значениями для чар. for (int i = 0; i <= 4; i++) { comboBox.Items.Add(i.ToString()); } } else { // Проставить значение "0" и не отображать ComboBox, поскольку уровень меньше 4. hit.Item.SubItems[enchantmentColumnIndex].Text = "0"; return; // Здесь возвращаемся, не добавляя ComboBox в контрол. } comboBox.SelectedItem = hit.SubItem.Text; } controlToDisplay = comboBox; // Установка ComboBox как контрола для отображения } // Добавление и отображение контрола, если он был создан if (controlToDisplay != null) { hit.Item.ListView.Parent.Controls.Add(controlToDisplay); controlToDisplay.BringToFront(); controlToDisplay.Visible = true; controlToDisplay.Focus(); } } } private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) { // Убедимся, что sender - это ComboBox. ComboBox comboBox = sender as ComboBox; if (comboBox == null) return; // Получение связанного ListViewItem из Tag ComboBox’а. ListViewItem listViewItem = comboBox.Tag as ListViewItem; if (listViewItem == null) return; int subItemIndex = 0; if (comboBox.Name == "level") { subItemIndex = levelColumnIndex; // Назначаем индекс для колонки уровня } else if (comboBox.Name == "enchantment") { subItemIndex = enchantmentColumnIndex; // Назначаем индекс для колонки чар } if (comboBox.SelectedItem != null) { listViewItem.SubItems[subItemIndex].Text = comboBox.SelectedItem.ToString(); // Обновляем значение в нужной колонке Item selectedItem = listViewItem.Tag as Item; // Обновляем иконку, если она изменилась из-за нового уровня или зачарования if (selectedItem != null) { UpdateItemIcon(listViewItem, selectedItem); } } // Скрытие ComboBox после выбора значения. comboBox.Visible = false; // Убрать фокус с ComboBox и вернуть его на ListView listViewItem.ListView.Focus(); listViewItem.ListView.SelectedItems.Clear(); } private void LevelComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox levelComboBox = sender as ComboBox; if (levelComboBox == null || !(levelComboBox.Tag is ListViewItem listViewItem)) return; int newLevel = int.TryParse(levelComboBox.SelectedItem.ToString(), out int levelValue) ? levelValue : 0; listViewItem.SubItems[levelColumnIndex].Text = newLevel.ToString(); ComboBox enchantmentComboBox = listViewItem.ListView.Controls.OfType<ComboBox>().FirstOrDefault(cb => cb.Tag == listViewItem && cb.Name == "enchantment"); if (enchantmentComboBox == null) { enchantmentComboBox = new ComboBox { Bounds = listViewItem.SubItems[enchantmentColumnIndex].Bounds, DropDownStyle = ComboBoxStyle.DropDownList, Tag = listViewItem, Name = "enchantment" }; enchantmentComboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged; listViewItem.ListView.Controls.Add(enchantmentComboBox); } UpdateEnchantmentComboBox(enchantmentComboBox, newLevel, listViewItem); listViewItem.SubItems[enchantmentColumnIndex].Text = "0"; Item selectedItem = listViewItem.Tag as Item; if (selectedItem != null) { selectedItem.Level = newLevel; // Обновляем уровень в объекте Item UpdateItemIcon(listViewItem, selectedItem); // Обновляем иконку элемента в ListView } } private void UpdateEnchantmentComboBox(ComboBox enchantmentComboBox, int level, ListViewItem listViewItem = null) { // Clear the items in the enchantment ComboBox. enchantmentComboBox.Items.Clear(); if (level >= 4) { // Populate the enchantment ComboBox with new items since level is greater than or equal to 4. for (int i = 0; i <= 4; i++) { enchantmentComboBox.Items.Add(i.ToString()); } } else { // Add a single item "0" since the level is less than 4. enchantmentComboBox.Items.Add("0"); // If a ListViewItem is provided, reset its enchantment value to "0". if (listViewItem != null) { listViewItem.SubItems[enchantmentColumnIndex].Text = "0"; } } enchantmentComboBox.SelectedIndex = 0; // Enable or disable the enchantment ComboBox based on the level. enchantmentComboBox.Enabled = level >= 4; int newCharm = int.TryParse(enchantmentComboBox.SelectedItem.ToString(), out int charmValue) ? charmValue : 0; Item selectedItem = listViewItem.Tag as Item; if (selectedItem != null) { selectedItem.Charms = newCharm; // Обновляем уровень в объекте Item UpdateItemIcon(listViewItem, selectedItem); // Обновляем иконку элемента в ListView } } private void TextBox_Leave(object sender, EventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { ListViewItem item = (ListViewItem)tb.Tag; if (item != null && item.ListView != null) { // Здесь номер колонки для количества - 2 (или другой индекс, если структура ListView иная) item.SubItems[2].Text = tb.Text; } item.ListView.Focus(); // Перемещаем фокус на ListView tb.Dispose(); // Уничтожаем TextBox } } private void UpdateItemIcon(ListViewItem listViewItem, Item item) { string imageKey = item.GetImageFileName(); LoadImageToImageList(imageKey); // Убедитесь, что изображение загружено listViewItem.ImageKey = imageKey; // Обновляем ключ изображения } } - Assistant
В вашем коде есть несколько методов для обработки изменения значений в ComboBox для уровня и чар элементов в ListView, но в методе
LevelComboBox_SelectedIndexChangedотсутствует обновление картинки после изменения уровня. Вам необходимо добавить логику обновления изображения вLevelComboBox_SelectedIndexChangedтаким же образом, как это сделано вComboBox_SelectedIndexChangedпосле изменения чар элемента.Вот как можно это реализовать:
- Сначала найдите и уберите из метода
ComboBox_SelectedIndexChangedследующий участок кода, так как он должен быть только в , чтобы избежать повторного обновления иконки:
- Сначала найдите и уберите из метода
- User
После изменения уровня картинка меняется, после изменения чар - нет private void UpdateItemIcon(ListViewItem listViewItem, Item item) { string imageKey = item.GetImageFileName(); LoadImageToImageList(imageKey); // Убедитесь, что изображение загружено listViewItem.ImageKey = imageKey; // Обновляем ключ изображения
} - Assistant
Если после изменения уровня картинка изменяется, а после изменения чар не изменяется, то необходимо убедиться, что метод
UpdateItemIconвызывается также и в методе, который обрабатывает изменение чар для элемента. Проверьте следующее:- Убедитесь, что метод
GetImageFileNameобъекта учитывает не только уровень, но и чар элемента:
- Убедитесь, что метод