Goran
Goran

Reputation: 6518

How to use x:class property in Binding?

I need to pass a View's class name as CommandParameter. How to do this?

<UserControl x:Name="window"
             x:Class="Test.Views.MyView"
             ...>

    <Grid x:Name="LayoutRoot" Margin="2">
        <Grid.Resources>
            <DataTemplate x:Key="tabItemTemplate">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center" >
                    <Button Command="{Binding DataContext.CloseCommand, ElementName=window}"
                            CommandParameter="{Binding x:Class, ElementName=window}">
                    </Button>
                </StackPanel>
            </DataTemplate>
        </Grid.Resources>
    </Grid>
</UserControl>

The result should be a string 'Test.Views.MyView'.

Upvotes: 1

Views: 1153

Answers (1)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84657

x:Class is only a directive and not a property so you won't be able to bind to it.

From MSDN

Configures XAML markup compilation to join partial classes between markup and code-behind. The code partial class is defined in a separate code file in a Common Language Specification (CLS) language, whereas the markup partial class is typically created by code generation during XAML compilation.

But you can get the same result from the FullName property of the Type. Use a Converter

CommandParameter="{Binding ElementName=window,
                           Path=.,
                           Converter={StaticResource GetTypeFullNameConverter}}"

GetTypeFullNameConverter

public class GetTypeFullNameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return null;
        }
        return value.GetType().FullName;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Upvotes: 1

Related Questions