如何在绑定中使用 x:class 属性

本文关键字:class 属性 绑定 | 更新日期: 2023-09-27 18:35:05

我需要将视图的类名作为命令参数传递。怎么做?

<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>

结果应该是一个字符串"Test.Views.MyView"。

如何在绑定中使用 x:class 属性

x:Class 只是一个指令,而不是一个属性,因此您将无法绑定到它。

来自 MSDN

配置 XAML 标记编译以联接 标记和代码隐藏。代码分部类在 公共语言规范 (CLS) 语言中的单独代码文件, 而标记分部类通常由代码创建 在 XAML 编译期间生成。

但是,您可以从 Type 的 FullName 属性获得相同的结果。使用转换器

CommandParameter="{Binding ElementName=window,
                           Path=.,
                           Converter={StaticResource 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();
    }
}