I want to change the visibility of a Grid
depending on whether the value of some TextBoxes
is larger than other TextBoxes
. I'm using MVVM and have the following code:
XAML
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis"/>
</UserControl.Resources>
<Grid x:Name="TimeError" Visibility="{Binding Path=IsTimeValid, Converter={StaticResource BoolToVis}}">
<TextBlock Text="Incorrect value"/>
</Grid>
<TextBox x:Name="TotalStarthh" MaxLength="2" FontSize="16" Width="28" Text="{Binding TotalStarthh}"/>
<more TextBoxes/>
In the ViewModel I parse the textBoxes
to an integer value and calculate the total time.
private string _TotalStarthh;
public string TotalStarthh
{
get { return _TotalStarthh; }
set { _TotalStarthh = value; NotifyPropertyChanged(); }
}
//The same for the other TextBoxes.
public int Totalstart()
{
int.TryParse(TotalStarthh, out int TShh);
int.TryParse(TotalStartmm, out int TSmm);
int.TryParse(TotalStartss, out int TSss);
//calculating hours:mins:sec to total seconds
//This can be over 24 hours so datetime is not used
int Totalstart = TShh * 3600 + TSmm * 60 + TSss;
return Totalstart;
}
public int Totalend()
{
int.TryParse(TotalEndhh, out int TEhh);
int.TryParse(TotalEndmm, out int TEmm);
int.TryParse(TotalEndss, out int TEss);
//calculating hours:mins:sec to total seconds
//This can be over 24 hours so datetime is not used
int Totalend = TEhh * 3600 + TEmm * 60 + TEss;
return Totalend;
}
// validate that start time is lower than end time.
public bool IsTimeValid
{
get { return (Totalstart > Totalend); }
set { NotifyPropertyChanged(); }
}
But this doesn't update the Visibility of the Grid
. Am I doing the NotifyPropertyChanged
incorrectly? I'm fairly new to mvvm and am still trying to grasp it. Thanks in advance.
NotifyPropertyChanged()
of yourIsTimeValid
. So you could addNotifyPropertyChanged(nameof(IsTimeValid));
to the setter of yourTotalStarthh
– Martin Backasch