When I enter text into a Textbox
, it updates two TextBlocks
at the same time. I'm trying to retrieve that value to save it to a sql database. I've temporarily set it up to display the value in a MessageBox.
ViewModel/Model:
private decimal _amount;
public decimal Amount
{
get
{
return _amount;
}
set
{
_amount = value;
OnPropertyChanged("Amount");
}
}
TextBox Binding:
<TextBox MaxLength="7" Visibility="{Binding Hide1, Converter={StaticResource BoolToVis},FallbackValue=Visible}" Text="{Binding Amount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" />
TextBlocks Binding:
<TextBlock Foreground="Black" Margin="0 0 0 0" VerticalAlignment="Top" Grid.Column="3" Text="{Binding Path=Amount}"/>
<TextBlock Grid.Column="3" Text="{Binding Amount}" Foreground="Black" Margin="0 0 0 0" VerticalAlignment="Bottom"/>
SaveCommand:
private async void Save()
{
try
{
MessageBox.Show(string.Format("{0}", Amount));
}
catch (DbEntityValidationException ex)
{
foreach (var en in ex.EntityValidationErrors)
{
var exceptionDialog = new MessageDialog
{
Message = { Text = string.Format("{0}, {1}", en.Entry.Entity.GetType().Name, en.Entry.State) }
};
await DialogHost.Show(exceptionDialog, "RootDialog");
foreach (var ve in en.ValidationErrors)
{
exceptionDialog = new MessageDialog
{
Message = { Text = string.Format("{0}, {1}", ve.PropertyName, ve.ErrorMessage) }
};
await DialogHost.Show(exceptionDialog, "RootDialog");
}
}
}
catch(Exception ex)
{
var exceptionDialog = new MessageDialog
{
Message = { Text = string.Format("{0}", ex) }
};
await DialogHost.Show(exceptionDialog, "RootDialog");
}
}
When I hit save, the MessageBox
displays 0.
EDIT: I've just remembered that I have the ViewModel
connected to two UserControls
. My TabLayout
, which handles the content of TabItems
; and Payroll which contains the save button and a TabControl
which loads TabLayout
into each TabItem
.
DataContext for both is:
public TabLayout()
{
InitializeComponent();
DataContext = new PayslipModel();
}
public Payroll()
{
InitializeComponent();
DataContext = new PayslipModel();
}
If you want both controls to share a
DataContext
then you can inject an instance from your composition root, i.e.App.Xaml.cs
The following probably doesn't match the way your application is laid out but should give you the idea. Down the road you can look at dependency injection and how to compose your object graph but this a start.App.xaml
App.xmal.cs
MainWindow.xaml.cs
UserControls