So in my WPF app, I am trying to figure out how to make this scenario as MVVM:
- Input text in a TextBox;
- On a button press, retrieve the input and pass it to a function that is for a command
I have tried doing something along the lines of this:
private string creatureName;
public string CreatureName
{
get {
return creatureName;
}
set
{
if(!string.Equals(creatureName, value))
{
creatureName = value;
OnPropertyChanged("CreatureName");
}
}
}
and textbox like this:
<TextBox x:Name="CreatureNameBox" Text="{Binding Path=CreatureName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" TextWrapping="NoWrap" FontFamily="Century Gothic" FontSize="16" Margin="150,0,150,16" MaxLines="1" Height="26" HorizontalAlignment="Stretch" VerticalAlignment="Center" Padding="5,3,5,3" MaxLength="100"/>
but it didn't work so I removed it.
Below is my code, if more code is needed let me know & I will update the ticket
TextBox:
<TextBox x:Name="CreatureNameBox" TextWrapping="NoWrap" FontFamily="Century Gothic" FontSize="16" Margin="150,0,150,16" MaxLines="1" Height="26" HorizontalAlignment="Stretch" VerticalAlignment="Center" Padding="5,3,5,3" MaxLength="100"/>
Button: Command is CreateNewCreature
<StackPanel>
<Button x:Name="CreateButton" Content="Create" FontWeight="Bold" FontFamily="Century Gothic" FontSize="18" Margin="10,3,10,0" Padding="0,5,0,5" Command="{Binding CreateNewCreature}" Height="34"/>
</StackPanel>
ViewModel: NewCreature() is where I want to pass the input value to as a string
namespace Creator.ViewModels
{
public class CreatureCreatorViewModel : ViewModelBase, INotifyPropertyChanged
{
public CreatureModel CreateNewCreature { get; set; }
public CreatureCreatorViewModel(NavigationStore navigationStore)
{
CreateNewCreature = new CreatureModel().NewCreature(*Retrieved TextBoxInput here*);
}
public CreatureCreatorViewModel()
{
}
}
}
Model:
namespace Creator.Models
{
public class CreatureModel : ISerializable
{
public string Name { get; set; }
public CreatureModel() { }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
}
public CreatureModel NewCreature(string creatureName)
{
CreatureModel newCreature = new CreatureModel
{
Name = creatureName
};
using (FileStream fs = File.Open("[Censored Directory]/Data/TEST.5e", FileMode.Create))
{
Byte[] info = new UTF8Encoding(true).GetBytes("Name : " + newCreature.Name);
fs.Write(info);
}
return newCreature;
}
public CreatureModel(SerializationInfo info, StreamingContext context)
{
Name = (string)info.GetValue("Name", typeof(string));
}
}
}