【发布时间】:2010-03-27 16:23:35
【问题描述】:
在下面的例子中:
- 我启动程序,输入文字,点击按钮,见上面的文字。按 ENTER 再次查看文字。
但是:
- 我启动程序,输入文本,按ENTER,查看no文本。
KeyDown 事件似乎无法访问绑定变量的当前值,就好像它始终是“one behind”。
我需要进行哪些更改,以便在按 ENTER 时可以访问文本框中的值,以便将其添加到聊天窗口?
alt text http://www.deviantsart.com/upload/1l20kdl.png
XAML:
<Window x:Class="TestScroll.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="290" Width="300" Background="#eee">
<StackPanel Margin="10">
<ScrollViewer Height="200" Width="260" Margin="0 0 0 10"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto">
<TextBlock Text="{Binding TextContent}"
Background="#fff"/>
</ScrollViewer>
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<TextBox x:Name="TheLineTextBox"
Text="{Binding TheLine}"
Width="205"
Margin="0 0 5 0"
KeyDown="TheLineTextBox_KeyDown"/>
<Button Content="Enter" Click="Button_Click"/>
</StackPanel>
</StackPanel>
</Window>
代码隐藏:
using System;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;
namespace TestScroll
{
public partial class Window1 : Window, INotifyPropertyChanged
{
#region ViewModelProperty: TextContent
private string _textContent;
public string TextContent
{
get
{
return _textContent;
}
set
{
_textContent = value;
OnPropertyChanged("TextContent");
}
}
#endregion
#region ViewModelProperty: TheLine
private string _theLine;
public string TheLine
{
get
{
return _theLine;
}
set
{
_theLine = value;
OnPropertyChanged("TheLine");
}
}
#endregion
public Window1()
{
InitializeComponent();
DataContext = this;
TheLineTextBox.Focus();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AddLine();
}
void AddLine()
{
TextContent += TheLine + Environment.NewLine;
}
private void TheLineTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
AddLine();
}
}
#region INotifiedProperty Block
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
【问题讨论】:
-
有趣,我现在正在调查事件顺序,但是 - 你为什么不使用 KeyUp(我通常用来支持体面的修饰符支持的那个)?同样的问题?
-
我试过KeyUp,效果一样。 KeyUp的优势是什么?你是什么意思体面的修饰符支持?
标签: c# wpf silverlight data-binding events