2012-05-23 32 views
1

我需要傳遞View的類名作爲CommandParameter。這個怎麼做?如何在Binding中使用x:class屬性?

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

回答

1

x:Class只是一個指令,而不是一個屬性,所以你將無法綁定到它。

From 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(); 
    } 
} 
+0

是的,我知道我可以用類型轉換器做到這一點,我只是好奇,如果它可以不。無論如何,我已經使用類似的東西,我添加了一個字符串屬性ViewModel,它做同樣的事情(GetType()。FullName) – Goran

相關問題