Reputation: 599
I need to enable/disable using XAML, a Picker based on the number of elements in it ItemsSource.
<Picker
ItemsSource="{Binding WoSpesaDett.DsTecnico}"
ItemDisplayBinding="{Binding Valore}"
SelectedItem="{Binding WoSpesaDett.Tecnico}"
IsEnabled="{Binding ???}"
Grid.Row="0" Grid.Column="3"/>
I have tried to use WoSpesaDett.DsTecnico.Count > 0
but it not works.
How can I achieve this?
Thank you!
Upvotes: 0
Views: 1340
Reputation: 12169
Note:
If you need to change the visibility of your Picker only once (not in dynamic manner), then create a converter like other answers pointing out.
Otherwise:
In theory dynamically hiding or showing a UI control is very simple. All you have to do is to introduce a boolean property in your model that should look like this for example:
public bool MyPickerShouldBeVisible => WoSpesaDett.DsTecnico.Count > 0;
Now the problem is that you need to notify your View
about changes related to MyPickerShouldBeVisible
. I am usually using Fody.PropertyChanged to handle the INotifyPropertyChange
stuff. Using it you could mark your DsTecnico
property with a special attribute AlsoNotifyFor(nameof(MyPickerShouldBeVisible))
to make this solution work.
Here is a full example, ViewModel data is simplified:
// INotifyPropertyChanged should be handled by `Fody.PropertyChanged`
public class MyViewModel : INotifyPropertyChanged
{
public IList<string> MyData { get; set; }
[AlsoNotifyFor(nameof(MyPickerShouldBeVisible))]
public bool ShouldShowPicker => MyData.Any();
}
Using the example above, will result in a dynamic behaviour of you picker.
Upvotes: 1
Reputation: 74124
IValueConverter
for integer to bool:
public class IntToBooleanConverter : IValueConverter
{
public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
{
int minimumLength = System.Convert.ToInt32 (parameter);
return (int)value >= minimumLength;
}
public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException ();
}
}
Upvotes: 1
Reputation: 1268
You can either create a bool in your binding context:
public bool PickerShouldBeEnabled
{
get { return WoSpesaDett.DsTecnico.Count > 0; } //returns true if there are more than 0 elements
}
or for better performance use linq "Any()", if u just wanna enable it if there are any elements in the list
public bool PickerShouldBeEnabled
{
get { return WoSpesaDett.DsTecnico.Any(); } //returns true if there are any elements
}
Or you can create an IValueConverter that takes the list as the value and returns true based on the count of the list elements. I could give you a basic converter for this situation as well.
Upvotes: 0