'How can I set the visibility of a label in XAML so it becomes visible where the Text property of that label is not null?
How can I set the visibility of a label in XAML so it becomes visible where the Text property of that label is not null?
I have this code:
<Label Grid.Row="0" Text="*" IsVisible="emptyLabel1 == null"/>
<Label Grid.Row="0" Text="{Binding EmptyLabel1}" IsVisible="emptyLabel1 == null"/>
<Label Grid.Row="1" Text="*" IsVisible="emptyLabel2 == null"/>
<Label Grid.Row="1" Text="{Binding EmptyLabel2}" IsVisible="emptyLabel2 == null"/>
In my VM it looks like this:
private string emptyLabel1;
private string emptyLabel2;
public string EmptyLabel1
{
get { return emptyLabel1; }
set
{
if (value != emptyLabel1)
{
emptyLabel1 = value;
NotifyPropertyChanged("EmptyLabel1");
}
}
}
public string EmptyLabel2
{
get { return emptyLabel2; }
set
{
if (value != emptyLabel2)
{
emptyLabel2 = value;
NotifyPropertyChanged("EmptyLabel2");
}
}
}
My problem is that it seems like I cannot put any conditional kind of check into the IsVisible.
Solution 1:[1]
I haven't tried this but to set visibility of Label in xaml need to do like this
<Label IsVisible="{Binding EmptyLabel1,
Converter={StaticResource StringNullOrEmptyBoolConverter}"
Text="{Binding EmptyLabel1}/>
For more information check this
Solution 2:[2]
Based on what Markus Michel showed in his comment I was able to implement the desired functionality. Here is my complete implementation. Needless to say, this is MVVM.
The XAML binds to two methods, MyCountRate and ShowMyCountRate. When MyCountRate is assigned in the code it not only calls RaisePropertyChanged on MyCountRate to update the display, it also calls it on ShowMyCountRate to update the visibility of the label if it is not null or 0. Thank you Markus!
<Label Text="{Binding MyCountRate, StringFormat='CPS: {0}'}"
FontSize="Small"
IsVisible="{Binding ShowMyCountRate}"
HorizontalTextAlignment="Center"></Label>
public bool ShowMyCountRate
{
get {
return ( (!string.IsNullOrEmpty(_myCountRate))
&& (int.Parse(_myCountRate) > 0));
}
}
private string _myCountRate;
public string MyCountRate
{
get => _myCountRate;
set
{
_myCountRate = value;
RaisePropertyChanged(() => MyCountRate);
RaisePropertyChanged(() => ShowMyCountRate);
// take any additional actions here which are required when MyCountRate is upcountRated
}
}
MyCountRate = waypoint.CountRate.ToString();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R15 |
| Solution 2 | charles young |
