You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF技术问题:如何将TextBlock的值传入GetSummonerDTO方法

解决WPF中TextBox值传入GetSummonerDTO方法的问题

看起来你已经搭建了基础的实现框架,我们可以把这个流程梳理得更清晰,确保TextBox的输入值能正确传递到GetSummonerDTO方法中,同时优化代码的健壮性:

1. 确保ViewModel绑定的正确性

首先你的ViewModel需要实现INotifyPropertyChanged接口,这样TextBox的输入才能实时同步到ViewModel的属性里:

public class MainViewModel : INotifyPropertyChanged
{
    private string _summonerNameDTO;
    public string SummonerNameDTO
    {
        get => _summonerNameDTO;
        set
        {
            _summonerNameDTO = value;
            OnPropertyChanged(nameof(SummonerNameDTO));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

2. 优化按钮点击事件的逻辑

你的原代码已经在传递值,但可以增加空值校验和结果判断,避免无效请求和提升用户体验:

private readonly SummonerDTOService _summonerDTOService;
private readonly MainViewModel _viewModel;

public MainWindow()
{
    InitializeComponent();
    _viewModel = new MainViewModel();
    _summonerDTOService = new SummonerDTOService();
    DataContext = _viewModel; // 必须设置DataContext,否则绑定不生效
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    // 先校验输入是否为空
    if (string.IsNullOrWhiteSpace(_viewModel.SummonerNameDTO))
    {
        MessageBox.Show("请输入召唤师名称!");
        return;
    }

    var summonerResponse = _summonerDTOService.GetSummonerDTO(_viewModel.SummonerNameDTO);
    if (summonerResponse != null)
    {
        string summonerId = summonerResponse.Id;
        // 这里可以添加后续逻辑,比如把ID显示到界面
        MessageBox.Show($"获取到召唤师ID:{summonerId}");
    }
    else
    {
        MessageBox.Show("未找到该召唤师,请检查名称或网络连接!");
    }
}

3. 完善服务类的错误处理

原服务类在请求失败时直接返回default,我们可以增加日志输出,方便排查问题:

public class SummonerDTOService
{
    private readonly RestClient _client;
    // 建议把API Key放到配置文件,不要硬编码在这里
    private const string ApiKey = "your-real-api-key";

    public SummonerDTOService()
    {
        _client = new RestClient("https://euw1.api.riotgames.com/lol/summoner/v4/summoners/");
    }

    public SummonerDTOResponse GetSummonerDTO(string summonerName)
    {
        if (string.IsNullOrWhiteSpace(summonerName))
            return null;

        var request = new RestRequest("by-name/{summonerName}")
            .AddParameter("summonerName", summonerName, ParameterType.UrlSegment)
            .AddParameter("api_key", ApiKey);

        var response = _client.Execute<SummonerDTOResponse>(request);
        
        if (!response.IsSuccessful)
        {
            // 输出错误信息方便调试
            System.Diagnostics.Debug.WriteLine($"API请求失败:状态码{response.StatusCode},错误信息:{response.ErrorMessage}");
            return null;
        }

        return response.Data;
    }
}

public class SummonerDTOResponse
{
    public string Id { get; set; }
    // 可以根据Riot API文档添加更多属性,比如Name、AccountId等
}

几个关键注意点

  • 一定要设置DataContext,否则TextBox的绑定无法和ViewModel联动
  • 绝对不要硬编码API Key,推荐用配置文件(比如appsettings.json)来管理敏感信息
  • 增加空值校验和错误处理,能有效避免程序崩溃,同时给用户明确的反馈

内容的提问来源于stack exchange,提问作者user13762401

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:02:50