如何在TextBox中键入新字符后如何进行数据绑定更新?
我正在学习WPF中的绑定,现在我已经陷入了(希望)简单的问题 .
我有一个简单的FileLister类,您可以在其中设置Path属性,然后它将在您访问FileNames属性时为您提供文件列表 . 这是 class :
class FileLister:INotifyPropertyChanged {
private string _path = "";
public string Path {
get {
return _path;
}
set {
if (_path.Equals(value)) return;
_path = value;
OnPropertyChanged("Path");
OnPropertyChanged("FileNames");
}
}
public List<String> FileNames {
get {
return getListing(Path);
}
}
private List<string> getListing(string path) {
DirectoryInfo dir = new DirectoryInfo(path);
List<string> result = new List<string>();
if (!dir.Exists) return result;
foreach (FileInfo fi in dir.GetFiles()) {
result.Add(fi.Name);
}
return result;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string property) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(property));
}
}
}
我在这个非常简单的应用程序中使用FileLister作为StaticResource:
<Window x:Class="WpfTest4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfTest4"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:FileLister x:Key="fileLister" Path="d:\temp" />
</Window.Resources>
<Grid>
<TextBox Text="{Binding Source={StaticResource fileLister}, Path=Path, Mode=TwoWay}"
Height="25" Margin="12,12,12,0" VerticalAlignment="Top" />
<ListBox Margin="12,43,12,12" Name="listBox1" ItemsSource="{Binding Source={StaticResource ResourceKey=fileLister}, Path=FileNames}"/>
</Grid>
</Window>
绑定工作正常 . 如果我更改文本框中的值,然后在其外部单击,则列表框内容将更新(只要路径存在) .
问题是我想在输入新字符后立即更新,而不是等到文本框失去焦点 .
我怎样才能做到这一点?有没有办法在xaml中直接执行此操作,还是必须在框中处理TextChanged或TextInput事件?
3 回答
在文本框绑定中,您所要做的就是设置
UpdateSourceTrigger=PropertyChanged
.您必须将
UpdateSourceTrigger
属性设置为PropertyChanged
突然,滑块和相关TextBox之间的数据绑定造成了麻烦 . 最后我找到了原因并且可以解决它 . 我使用的转换器:
在XAML中
进一步定义TextBox