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

UWP开发:XAML.cs无法定位DataTemplate中的TextBox问题求助

解决DataTemplate中TextBox无法在后台直接访问的问题

嘿,我明白你遇到的问题了——你在GridView的DataTemplate里定义了AmountBox,但后台代码里直接用名称找不到它,这是因为DataTemplate里的控件属于每个GridView项的模板实例,不是页面的直接子元素,所以不能像访问页面上的普通控件那样直接通过x:Name获取。下面给你两种解决方案,推荐第一种更优雅的方式:

方案一:通过数据绑定获取值(推荐,符合MVVM思想)

这种方式是把TextBox的输入值绑定到你的Merchandise数据类的一个属性上,这样点击按钮时直接从对应的数据对象里取数值,不需要手动查找控件。

步骤1:给Merchandise类添加补货数量属性

首先修改你的Merchandise类,添加一个RestockAmount属性,并且实现INotifyPropertyChanged接口(这样绑定才能双向生效,输入值变化时更新到对象里):

public class Merchandise : INotifyPropertyChanged
{
    // 你的原有属性(Name、Supplier、Stock、CoverImage等)...
    
    private int _restockAmount;
    public int RestockAmount
    {
        get => _restockAmount;
        set
        {
            _restockAmount = value;
            OnPropertyChanged(nameof(RestockAmount));
        }
    }

    // 实现INotifyPropertyChanged接口
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

步骤2:修改XAML里的TextBox绑定

把TextBox的Text属性绑定到刚加的RestockAmount,设置Mode=TwoWay确保输入值能同步到数据对象:

<TextBox x:Name="AmountBox" FontSize="15" Text="{x:Bind RestockAmount, Mode=TwoWay}"/>

步骤3:修改Submit_Click事件获取数值

点击按钮时,通过按钮的DataContext拿到当前对应的Merchandise对象,直接取它的RestockAmount:

private void Submit_Click(object sender, RoutedEventArgs e)
{
    var submitBtn = sender as Button;
    var currentMerch = submitBtn.DataContext as Merchandise;
    
    if (currentMerch != null)
    {
        // 调用AddToStock,传入补货数量和商品名称
        AddToStock(currentMerch.RestockAmount, currentMerch.Name);
        // 清空输入框
        currentMerch.RestockAmount = 0;
    }
}

方案二:通过可视化树查找控件(不推荐,耦合性高)

如果暂时不想修改数据类,也可以通过遍历可视化树找到AmountBox,但这种方式依赖模板的结构,一旦模板布局变化(比如把StackPanel换成Grid),代码就会失效,所以只作为临时方案:

private void Submit_Click(object sender, RoutedEventArgs e)
{
    var submitBtn = sender as Button;
    // 找到按钮的父容器StackPanel
    var parentPanel = submitBtn.Parent as StackPanel;
    
    if (parentPanel != null)
    {
        // 在StackPanel里查找名为AmountBox的TextBox
        var amountBox = parentPanel.FindName("AmountBox") as TextBox;
        if (amountBox != null && int.TryParse(amountBox.Text, out int restockAmount))
        {
            var currentMerch = parentPanel.DataContext as Merchandise;
            if (currentMerch != null)
            {
                AddToStock(restockAmount, currentMerch.Name);
                amountBox.Text = string.Empty;
            }
        }
    }
}

额外提醒:你的原代码有个小问题

原代码里Submit_Click调用AddToStock()时没有传参数,但AddToStock方法需要int amount和string itemName两个参数,这会导致编译错误,上面的两种方案里已经修正了这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 17:57:48