【问题标题】:Converting TextBox.Text to Int. (No-Code Behind) [closed]将 TextBox.Text 转换为 Int。 (无代码背后)[关闭]
【发布时间】:2015-07-08 03:07:36
【问题描述】:

我在互联网上没有找到可以解决我的问题的解决方案。所以我真的希望有人可以帮助我。

基本上就是标题所说的。我有这个

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);
    }

我在视图中绑定到一个 Button,看起来像这样,非常简单。

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

GetChampion 方法需要一个 Champion 的 ID,我在文本框中输入该 ID,然后将其作为“id”传递,因此我尝试将其转换为 int。我明白了(如上),我明白了

" RiotApiApplication.exe 中出现“System.InvalidCastException”类型的异常,但未在用户代码中处理 附加信息:指定的演员表无效。”

我试过 Convert.ToInt32(id) 我明白了:

无法将“System.Windows.Controls.TextBox”类型的对象转换为“System.IConvertible”类型。

所以我的下一个尝试是我尝试包含一个转换器,该转换器接受文本框的输入并将其转换为整数。例如。 “Aatrox” == 266,看起来像这样。 (我知道这不是最好的解决方案,但我只想让它先工作)

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

但仍然遇到同样的问题。 所以我尝试创建一个新的 MyCommand 类,它是 Generic 所以它返回 Integer 并且仍然没有希望。

任何人都可以找到解决方案或以正确的方式帮助我。我有点卡住了,不知道该怎么办。我可以编写一个接受字符串的方法,但这会破坏使用库的目的。

【问题讨论】:

    标签: c# wpf xaml binding icommand


    【解决方案1】:

    您引用了错误的对象作为您的命令参数 - 您将文本框本身传递给您的命令,而不是包含文本元素。 为了解决这个问题,您必须在命令参数绑定中使用“路径”语法:

    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 2011-07-28
      相关资源
      最近更新 更多