Search code examples
c#wpfxamlbindingicommand

Converting TextBox.Text to Int. (No-Code Behind)


I have not found a solution on the internet that will solve my issue. So I really hope someone can help me.

So basically what the Title says. I have this

public MyCommand Champion
    {
        get
        {
            return new MyCommand((id) =>
            {
                ChampionById(id);
            });
        }
        set { _champion = value; }
    }

    private async void ChampionById(object id)
    {
        _staticRiotApi.GetChampion(Region.euw, (int)id);
    }

which I bind to a Button in my view, which looks like this, pretty simple.

 <Button Content="Search By Id" Command="{Binding Champion}" CommandParameter="{Binding ElementName=championId}">
            </Button>
    <TextBox Grid.Row="0" Grid.Column="1" Name="championId"></TextBox>

The method GetChampion needs an ID of the Champion, which I enter in the text box, which then will be passed as "id", so I tried casting it to int. I get this(like above) and I get this

" An exception of type 'System.InvalidCastException' occurred in RiotApiApplication.exe but was not handled in user code Additional information: Specified cast is not valid."

I tried Convert.ToInt32(id) i get this:

Unable to cast object of type 'System.Windows.Controls.TextBox' to type 'System.IConvertible'.

So my next try was I tried including a converter which takes the input of the textbox and convert it to an integer. Eg. "Aatrox" == 266, which looks like this. (I know it isnt the best solution, but I just want it to work first)

switch (value as string)
        {
            case "Aatrox":
                value = 266;
                break;
        }
        return value;

But still get the same issue. So I tried creating a new MyCommand class which is Generic so it returned Integer and still no hope.

Can anybody find a solution or help me the right way. I am kinda stuck and don't know what to do. I can write a method that takes a string, but that would defeat the purpose of using a library.


Solution

  • You are referencing the wrong object as your commandparameter - you pass the textbox itself to your command instead of the containing textelement. In order to fix this, you have to use the "Path" syntax in your commandparameter binding:

    <Button Content="Search By Id" Command="{Binding Champion}" CommandParameter={Binding ElementName=championId, Path=Text}">
    </Button>
    <TextBox Grid.Row="0" Grid.Column="1" Name="championId"></TextBox>