GiantDwarf
GiantDwarf

Reputation: 5

How to add variables and link them to a combobox from an external file?

I have a program where the user can choose a "class" of ships based off a combobox. Currently all the stats and classes are hard coded into the program. The problem is I want to be able to add extra ship types as needed. Preferably in a simple way that my friend (who knows almost nothing about code) and also add ships (the plan is once I finish, I'll give a copy to him to use). Each ship uses a name and 3 stats. The current hardcoded codes I have is -

private void cmb_Class_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        shipClass = (cmb_Class.SelectedItem as ComboBoxItem).Content.ToString();
        if (shipClass == "Scout")
        {
            attack = 6;
            engine = 10;
            shield = 8;
        }
        if (shipClass == "Warship")
        {
            attack = 10;
            engine = 6;
            shield = 8;
        }
        if (shipClass == "Cargo")
        {
            attack = 8;
            engine = 6;
            shield = 10;
        }
        if (shipClass == "Starliner")
        {
            attack = 6;
            engine = 8;
            shield = 10;
        }
        if (shipClass == "Transport")
        {
            attack = 8;
            engine = 10;
            shield = 6;
        }
        if (shipClass == "Luxury")
        {
            attack = 8;
            engine = 8;
            shield = 8;
        }

        lbl_Attack.Content = attack;
        lbl_Engine.Content = engine;
        lbl_Shield.Content = shield;
    }

The items in the combobox cmb_Class is all hardcoded into the WPF forms xml and the labels are just how I'm showing the stats.

Bonus issue: I can just make a secondary file for a similar group of "species" and their stats (yes, it's a sci-fi RPG type thing), but if there's a simple way to make them all in the same file, that'd be great.

Upvotes: 0

Views: 456

Answers (1)

flo_badea
flo_badea

Reputation: 784

here is what you might like to use. it's not using XML, it's using CSV but you can easily extend it.

first you'll need a class to represent your ships, like below.

public class Ship
{
    public string Class { get; set; }
    public int Attack { get; set; }
    public int Engine { get; set; }
    public int Shield { get; set; }
}

After this you'll need a way to read your ships from some sort of data source: file, DB, etc. this source can change ofter so you'll be better of abstracting this behind an interface like below.

interface IShipRepository
{
    List<Ship> GetShips();
}

After you decide where you'll get the ships from you can write that in an implementation of the IShipRepository interface. The code below shows how to read it from a CSV file.

public class CSVShipRepository : IShipRepository
{
    private readonly string filePath;
    public CSVShipRepository(string filePath)
    {
        if (string.IsNullOrEmpty(filePath))
            throw new ArgumentNullException("filePath");
        this.filePath = filePath;
    }
    public List<Ship> GetShips()
    {
        var res = new List<Ship>();
        try
        {
            string fileData;
            using (var sr = new StreamReader(filePath))
            {
                fileData = sr.ReadToEnd();
            }
            //class, attack, engine, shield
            string[] lines = fileData.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            bool first = true;
            foreach (var line in lines)
            {
                if (first)
                {//jump over the first line (the CSV header line)
                    first = false; continue;
                }
                string[] values = line.Split(new string[] { "," }, StringSplitOptions.None)
                    .Select(p=>p.Trim()).ToArray();
                if (values.Length != 4) continue;

                var ship = new Ship() { 
                    Class=values[0],
                    Attack=int.Parse(values[1]),
                    Engine = int.Parse(values[2]),
                    Shield = int.Parse(values[3]),
                };

                res.Add(ship);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("error reading file: " + ex.Message);
        }

        return res;
    }
}

all you have to do now is to use this CSVShipRepository in your code behind. we'll use a little data binding for this like below.

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private IShipRepository repository = new CSVShipRepository("d:\\test_data.csv");
    private List<Ship> ships;
    private Ship selectedShip;
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    public List<Ship> Ships
    {
        get
        {
            if (ships == null)
                ships = repository.GetShips();
            return ships;
        }
    }
    public Ship SelectedShip
    {
        get { return selectedShip; }
        set
        {
            if (selectedShip == value) return;
            selectedShip = value;
            NotifyChanged("SelectedShip");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

the corresponding XAML is below.

<ComboBox ItemsSource="{Binding Ships}" 
              SelectedItem="{Binding SelectedShip, Mode=TwoWay}" Margin="2">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Class}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Grid.Row="1" Text="{Binding SelectedShip.Attack}" Margin="3" />
<TextBlock Grid.Row="2" Text="{Binding SelectedShip.Engine}" Margin="3" />
<TextBlock Grid.Row="3" Text="{Binding SelectedShip.Shield}" Margin="3" />

hope this is what you need. it's simpler than XML since your friend doesn't know code. and here is some sample data

class, attack, engine, shield
demo, 1, 2, 3
demo2, 4, 5, 6

Upvotes: 1

Related Questions