My app has to load a .txt
file from the file system, read it and put its text into a TextBlock
, but I don't know how to connect my Button
to my view model so my text block that is bound to a property in it displays this text.
Let's repeat what I want my app to do:
- A user clicks on the load button and he chooses a
.txt
file - The text from the file is assigned to the
NumbersString
property - The text block loads this text from the
NumbersString
property
I dont know how to get step 2 to work.
XAML
<Button Name="load" Background="Pink" Click="load_Click">Load File</Button>
<TextBox x:Name="numbers1" Text="{Binding NumbersString, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True"/>
Code-behind XAML
There is a mistake my view model property NumbersString
. It should be connected to the button.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new numbersViewModel();
}
public void load_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
NumbersString = File.ReadAllText(openFileDialog.FileName);
}
}
View model
class numbersViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private numbersModel _model;
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler evt = PropertyChanged;
if (evt != null)
evt(this, new PropertyChangedEventArgs(propertyName));
}
// iI want my text block to take the string from here
public string NumbersString
{
get { return _model.numbersString; }
set
{
if (value != _model.numbersString)
{
_model.numbersString = value;
RaisePropertyChanged("numbers1");
}
}
}
}
Model
private string model="";
public string numbersString
{
get
{
return model;
}
set
{
model = value;
}
}