lud*_*det 73 c# data-binding wpf xaml textbox
我正在学习WPF中的绑定,现在我已经陷入了(希望)简单的问题.
我有一个简单的FileLister类,您可以在其中设置Path属性,然后它将在您访问FileNames属性时为您提供文件列表.这是班级:
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在这个非常简单的应用程序中使用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>
Run Code Online (Sandbox Code Playgroud)
绑定工作正常.如果我更改文本框中的值,然后在其外部单击,则列表框内容将更新(只要路径存在).
问题是我想在输入新字符后立即更新,而不是等到文本框失去焦点.
我怎样才能做到这一点?有没有办法在xaml中直接执行此操作,还是必须在框中处理TextChanged或TextInput事件?
Edu*_*tes 30
您必须将UpdateSourceTrigger属性设置为PropertyChanged
<TextBox Text="{Binding Source={StaticResource fileLister}, Path=Path, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Height="25" Margin="12,12,12,0" VerticalAlignment="Top"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31103 次 |
| 最近记录: |