Reputation: 125
I have set a border visibility binding to a variable in a class in Views, called P, where P is a Boolean type. I have another variable in a class in ViewModels, called M, where M is a Dictionary and the Enum consists of three elements, something like A, B and C. How could I bind P to M.value in which if P is false, M.value is set to A, and if P is true, M.value is set to B or C (depends on some condition) so that the border is visible when M.value is B or C and it is not visible when M.value is A?
So far I have implemented binding of border visibility to P already and it works (when P is true, it is visible and when P is false, it is not visible).
enum E {
A,B,C
}
public class ClassInViews {
private bool picked = false;
public bool Picked {get; set;}
}
public class ClassInViewModels {
private Dictionary<(...An arbitrary class in Models),E> M;
}
Upvotes: 0
Views: 659
Reputation: 105
Since you want to bind it to changes of the Dictionary, I would then use an ObservableDictionary and respond to any change within the collection by raising a changed event for the "Picked" property. So your ViewModel has to implement INotifyPropertyChanged.
Then the simplest thing would be to write your logic into the getter of P.
public bool Picked
{
get
{
/*Your logic here*/
}
}
Second Option: You could create an IValueConverter transforming your given Directory to a Visibility.
public class Bool2VisibilityConverter : MarkupExtension, IValueConverter
{
static Bool2VisibilityConverter _converter;
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (_converter == null)
{
_converter = new Bool2VisibilityConverter();
}
return _converter;
}
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var dic = value as ObservableDictionaray<YourTypesHere>;
if (dic == null)
return Visibility.Collapsed;
bool visible = /* Check the Dictionary with your logic */;
return (bool) visible ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementexException();
}
#endregion
}
Then you can simply use it to transform the Dictionary:
<Button Visibility="{Binding Dictioanry, Converter={conv:Bool2VisibilityConverter}}" />
Upvotes: 1