我有一个功能,我想在更新许多不同的文本框后运行,是否可以在更新后监听通用事件而不是特定事件?
所以不是对函数进行 100 次单独调用,而是只有一个监听器?
编辑:看起来我们正在使用 MVVM 和传统代码的组合。
这是其中一个文本框:
<TextBox Text="{Binding APhaseFrom}" x:Name="txtFromWhereA" TabIndex="26" HorizontalContentAlignment="Center" HorizontalAlignment="Left" Height="48" TextWrapping="NoWrap" VerticalAlignment="Top" Width="261" FontSize="26" FontWeight="Bold" BorderBrush="Black" BorderThickness="1" Margin="289,656,0,0" GotMouseCapture="txtFromWhereA_GotMouseCapture" GotFocus="txtFromWhereA_GotFocus" Grid.Row="3" />
View 模型中的代码:
public string APhaseFrom
{
get { return new string((char[])_f.Rows[1].GetValue("Alpha09")); }
set
{
if (value.Length <= 35)
{
_f.Rows[1].SetValue("Alpha09", value);
}
else
{
MessageBox.Show("Error: String length Longer than 35 Characters.");
}
}
}
我们还对其他进程使用了一些命令:
public ICommand Updatesql
{
get;
internal set;
}
private void CreateUpdatesql()
{
Updatesql = new RelayCommand(UpdatesqlExecute);
}
private void UpdatesqlExecute()
{
_f.Update();
}
我应该使用命令还是只是将事件链接到 View 模型中的函数?
最佳答案
由于您使用的是 WPF,并且如果我正确理解了您的问题,那么 WPF 使用的 RoutedEvents 可能会在这里为您提供帮助。本质上,像 LostFocus
这样的事件TextBox 的事件将在您的 UI 层次结构中冒泡,并且可以由公共(public)父控件处理。考虑这段 XAML 和代码隐藏:
<StackPanel TextBox.LostFocus="TextBoxLostFocus">
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
</StackPanel>
代码隐藏:
private void TextBoxLostFocus(object sender, RoutedEventArgs e)
{
MessageBox.Show("Lost Focus!");
}
您会发现当焦点丢失时,会为三个文本框中的任何一个调用事件处理程序。
sender
参数或 e.Source
可用于查找触发事件的文本框。这种模式适用于任何
RoutedEvent
, 所以像 Button.Click
或 TextBox.TextChanged
以这种方式可以捕获更多。
关于c# - 监听通用事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20661988/