1

我需要将视图的类名作为 CommandParameter 传递。这该怎么做?

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

4

1 回答 1

1

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

来自 MSDN

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

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

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();
    }
}
于 2012-05-23T22:42:39.227 回答