2011-05-15 9 views
0

WPFを使用して、GroupBoxのヘッダーをポリモーフィッククラスの型名にバインドします。ですから、ElementというクラスとBasicElementやAdvancedElementのようなElementから派生した2つのクラスがある場合、GroupBoxのヘッダーに "BasicElement"や "AdvancedElement"と言ってもらいたいです。私はGroupBoxのために使用しているxamlです。 ItemsControlで使用されているDataTemplateの一部です。私は、Path = DerivedTypeNameOf(group)の代わりに、XAMLの何かを期待しています。ここで、groupはgroups配列の各グループです。WPFがクラスの型名へのパスをバインドする

TheDataのObjectInstanceが、いくつかのBasicGroupsとAdvancedGroupsの配列を保持するGroupSetの有効なインスタンスに設定されていることに注意してください。ここで

は、適切なコードビハインドクラスです:

public class Group 
{ 
    public string groupName; 

    public string df_groupName 
    { 
     get { return this.groupName; } 
     set { this.groupName = value; } 
    } 
} 

public class BasicGroup : Group 
{ 

} 

public class AdvancedGroup : Group 
{ 

} 

public class GroupSet 
{ 
    public Group [] groups; 

    public Group [] df_groups 
    { 
     get { return this.groups; } 
     set { this.groups = value; } 
    } 
}; 

はここにXAMLです:

<UserControl.Resources> 
    <ResourceDictionary> 
     <ObjectDataProvider x:Key="TheData" /> 

     <DataTemplate x:Key="GroupTemplate"> 
      <GroupBox Header="{Binding Path=DerivedTypeNameOf(group)}"> 
       <TextBox Text="This is some text"/> 
      </GroupBox> 
     </DataTemplate> 

    </ResourceDictionary> 
</UserControl.Resources> 

    <ItemsControl ItemsSource="{Binding Source={StaticResource TheData}, Path=groups}" ItemTemplate="{StaticResource GroupTemplate}"> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <StackPanel /> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
    </ItemsControl> 
+0

あなたの質問は何ですか? – miguel

答えて

0

理由だけではなく、あなたのベースクラスに

public abstract string DerivedTypeName { get; set; } 

を追加し、それを上書きしませんそれぞれの派生型は、単純に文字列にバインドしています。

2

あなたは、常にタイプを取得するためにValueConverterを使用することができます。

public class TypeNameConverter : IValueConverter { 
    public object Convert(object value, Type targetType, 
    object parameter, CultureInfo culture) { 
    return value.GetType().Name; 
    } 

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

あなたはそれが値を取得するプロパティを実装するために必要とせずに、あなたのコレクション内の任意の型を持つことができるようになります。さもなければ、ダビデが言っているようにして、結果を与えるためにプロパティを実装してください。基本クラスからの一般的な継承があれば、すべてのクラスに実装する必要はありません。 GetType()。Nameを使ってベースに実装するだけで、常に正しい値が得られます。

関連する問題