【发布时间】:2022-01-11 16:53:17
【问题描述】:
文件“sample.txt”位于 Assets 文件夹中,其中包含一行文本“hello, world”。 我想将其内容绑定到 Textblock 控件。
【问题讨论】:
标签: c# data-binding uwp
文件“sample.txt”位于 Assets 文件夹中,其中包含一行文本“hello, world”。 我想将其内容绑定到 Textblock 控件。
【问题讨论】:
标签: c# data-binding uwp
将TextBlock的Text属性设置为文件的内容:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.Loaded += async (s, e) =>
{
const string Filename = @"Assets\sample.txt";
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(Filename);
textBlock1.Text = await File.ReadAllTextAsync(file.Path);
};
}
}
【讨论】:
使用File.ReadAllText 从文件中提取文本并将其分配给实现INotifyPropertyChanged 的类的属性。将此属性绑定到TextBlock.Text 属性。
您的视图模型:
public class MainPageViewModel : INotifyPropertyChanged
{
private string text;
public event PropertyChangedEventHandler PropertyChanged;
public string Text
{
get => this.text;
set
{
this.text = value;
this.OnPropertyChanged(nameof(this.Text))
}
}
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
你的看法:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.Loaded += async (s, e) =>
{
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(@"Assets\sample.txt");
this.DataContext = new MainPageViewModel
{
Text = await File.ReadAllTextAsync(file.Path),
};
};
}
}
在 MainPage XAML 中:
<TextBlock Text="{x:Bind Text}"
要检测 txt 文件中的更改,请使用 FileSystemWatcher。
【讨论】: