Reputation: 6174
I would like to be able to pass the Type object of an interface as the ConverterParameter to my type converter. The idea is that I would like the converter to return a value based on whether or not the source value implements a specific interface.
I have a method that works if I pass the type name as a string, but I'd rather have it be a strongly typed value to avoid potential maintenance issues down the road and have compile time checking rather than relying on a failure at runtime.
Here is the converter I have that uses strings:
class InterfaceToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
var type = value.GetType();
if (type.GetInterface(parameter as string) != null)
{ return Visibility.Visible; }
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
It works great other than the potential maintenance problems outlined above.
This is how you might use it in xaml:
<TabItem Header="General"
Visibility="{Binding ConverterParameter=IMyType, Converter={StaticResource InterfaceToVisibilityConverter}}">
<TextBlock Text="Whatever Content Goes here."/>
</TabItem>
In the example above, it is checking the current DataContext to determine if it supports the interface IMyType and if so, the tab will be visible. If not, the tab will be collapsed. Very handy for creating UI's that are sensitive to what their data source is capable of.
Is there any way to accomplish what I would like to do?
Upvotes: 1
Views: 4078
Reputation: 44038
use the {x:Type}
Markup Extension:
TabItem Header="General"
Visibility="{Binding ConverterParameter={x:Type my:IMyType},
Converter={StaticResource InterfaceToVisibilityConverter}}">
Upvotes: 5