数据模板中 WPF 控件的事件处理程序

本文关键字:事件处理 程序 控件 WPF 数据 | 更新日期: 2023-09-27 18:33:10

我一直在使用WPF,遇到了与DataTemplates相关的问题。我有一个名为 DetailPage.xaml 的视图,这个视图使用一个名为 Detail.xaml 的数据模板。我向此数据模板添加了一个文本框,并且想要处理 TextChanged 事件。所以我做了这样的东西:

<DataTemplate x:Name="DetailContent">
    <Grid Margin="5" DataContext="{Binding Items[0]}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition MaxHeight="80"/>
        </Grid.RowDefinitions>
        <StackPanel Width="432">
            <TextBox Name="NumeroParadaTB" Text="{Binding NumeroParada}" MaxLength="5" TextChanged="NumeroParadaTB_TextChanged" />
        </StackPanel>
    </Grid>
</DataTemplate>

然后我在 DetailPage.xaml.cs 中创建和事件处理程序,如下所示:

protected async void NumeroParadaTB_TextChanged(object sender, TextChangedEventArgs e)
    {
        string nroParada = ((TextBox)sender).Text;
        if(!string.IsNullOrEmpty(nroParada) && nroParada.IsDigitsOnly() && nroParada.Length == 5)
        {
        }
    }

但是在运行时,会抛出错误,指出事件处理程序不存在。我想我以错误的方式使用事件处理程序。

谢谢!

数据模板中 WPF 控件的事件处理程序

由于您使用的是数据绑定,因此我假设您有一些具有NumeroParada属性的类:

public class SomeClass : INotifyPropertyChanged
{
    /* other code here */
    public string NumeroParada
    {
         get { return numeroParada; }
         set
         {
             if (numeroParada != value)
             {
                  numeroParada = value;
                  OnPropertyChanged("NumeroParada");
             }
         }
    }
    private string numeroParada;    
}

当 UI 将更新绑定源时,将触发此属性的资源库。这是您的"TextChanged"事件。

请注意,默认情况下,TextBox在失去焦点时更新Text属性。如果要在用户更改文本时执行任何操作,请更新绑定定义:

Text="{Binding NumeroParada, UpdateSourceTrigger=PropertyChanged}"

目前为止,一切都好。但是这个代码:

if(!string.IsNullOrEmpty(nroParada) && nroParada.IsDigitsOnly() && nroParada.Length == 5)

建议,您正在尝试实现用户输入的值验证。WPF 中的验证是一个相当大的主题,我建议您阅读类似内容以选择验证方法。

可以使用 Event to Command 逻辑,而不是添加事件处理程序。在 ViewModel 中创建一个命令,并将其绑定到 TextChanged 事件。

        <TextBox Text="{Binding SearchText, Mode=TwoWay}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="TextChanged">
                    <i:InvokeCommandAction Command="{Binding MyCommand}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </TextBox>

System.Windows.交互程序集中可用的交互触发器。