我想在文本框中添加点击事件,但我的代码不起作用。单击文本框时,事件不会运行。
以下是
背后的代码public class Day : INotifyPropertyChanged
{
public delegate void ClickEventHandler(object sender, ClickEventArgs e);
public event Application_IAD.TEST.Day.ClickEventHandler onClick;
protected virtual void onTheClick()
{
if (onClick != null) onClick(this, new ClickEventArgs(new Day()));
}
}
public class Cal : Control
{
public ObservableCollection<Day> Days { get; set; }
public event EventHandler<ClickEventArgs> DayClick;
public Cal()
{
DataContext = this;
CurrentDate = DateTime.Today;
DayNames = new ObservableCollection<string> {"Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"};
Days = new ObservableCollection<Day>();
BuildCalendar(DateTime.Today);
}
public void BuildCalendar(DateTime targetDate)
{
Days.Clear();
//Show 6 weeks each with 7 days = 42
for (int box = 1; box <= 42; box++)
{
Day day = new Day {Date = d, Enabled = true, IsTargetMonth = targetDate.Month == d.Month};
day.onClick += test;
}
}
private void test(object sender, ClickEventArgs e)
{
DayClick(this, new ClickEventArgs(sender as Day));
}
}
这是XAML
<Calen:Cal x:Name="Calendar" Margin="0,50,0,0" DayChanged="Calendar_DayChanged" DayClick="Calendar_DayClick"/>
我不知道错误在哪里或知道如何解决它。
答案 0 :(得分:0)
您可以通过两种不同的方式实现WPF TextBox控件(例如TextBox1)事件订阅,如下面的示例代码片段所示:
使用C#Lambda-expression(最短代码语法):
TextBox1.PreviewKeyDown += (s, e) => { //YOUR CODE};
更传统的方式(更长的语法):
TextBox1.PreviewMouseDown += (s, e) => TextBox_PreviewMouseDown(s, e);
private void TextBox_PreviewMouseDown(object sender, RoutedEventArgs e)
{
try
{
TextBox _tb = sender as TextBox;
// THE REST OF YOUR CODE
}
catch { }
}
与WPF TextBox相关的有用事件订阅示例:
TextBox1.TextChanged += (s, e) => { // YOUR CODE };
希望这可能会有所帮助。亲切的问候,