2012-04-02 24 views
0

我在C#代碼中創建一個TabControl。我將其ItemsSource綁定到集合並設置邊距。 出於某種原因,設置其DisplayMemberPath將無法正常工作。在C中設置TabControl的DisplayMemberPath#

_tabControl = new TabControl(); 
_tabControl.Margin = new Thickness(5); 
_tabControl.DisplayMemberPath = "Header"; 
_tabControl.SetBinding(ItemsControl.ItemsSourceProperty, itemsSourceBinding); 

集合中的每個項目都有一個名爲「Header」的屬性。

爲什麼這不起作用?

安德烈

編輯: 這裏是所有相關代碼:

public partial class VariationGroupPreviewOptionsView 
{ 
    public string Header { get; set; } 

    public VariationGroupPreviewOptionsView() 
    { 
     InitializeComponent(); 
     DataContext = new VariationGroupPreviewOptionsViewModel(); 
    } 
} 

private void OptionsCommandExecute() 
{ 
    var dlg = new OptionsDialog(); 
    dlg.ItemsSource = new List<ContentControl>() {new VariationGroupPreviewOptionsView(){Header = "Test"}}; 
    dlg.ShowDialog(); 
} 

public class OptionsDialog : Dialog 
{ 

    public static readonly DependencyProperty ItemsSourceProperty = 
     DependencyProperty.Register("ItemsSource", typeof (IEnumerable), typeof (OptionsDialog), new PropertyMetadata(default(IEnumerable))); 

    public IEnumerable ItemsSource 
    { 
     get { return (IEnumerable) GetValue(ItemsSourceProperty); } 
     set { SetValue(ItemsSourceProperty, value); } 
    } 

    private readonly TabControl _tabControl; 


    public OptionsDialog() 
    { 
     DataContext = this; 
     var itemsSourceBinding = new Binding(); 
     itemsSourceBinding.Path = new PropertyPath("ItemsSource"); 

     _tabControl = new TabControl(); 
     _tabControl.Margin = new Thickness(5); 
     _tabControl.DisplayMemberPath = "Header"; 
     _tabControl.SetBinding(ItemsControl.ItemsSourceProperty, itemsSourceBinding); 

     var recRectangle = new Rectangle(); 
     recRectangle.Margin = new Thickness(5); 
     recRectangle.Effect = (Effect)FindResource("MainDropShadowEffect"); 
     recRectangle.Fill = (Brush)FindResource("PanelBackgroundBrush"); 

     var grdGrid = new Grid(); 
     grdGrid.Children.Add(recRectangle); 
     grdGrid.Children.Add(_tabControl); 

     DialogContent = grdGrid; 
    } 
} 
+0

請描述「不起作用」。 – 2012-04-02 08:54:26

+0

TabItem標題爲空。 – Andre 2012-04-02 08:56:32

+0

沒有保證金? – 2012-04-02 08:57:12

回答

5

沒有違法,但你的代碼是一個令人費解的混亂,從真正的問題分心。如果你簡化你會看到設置DisplayMemberPath作品完全一樣,你想讓它:

XAML:

<TabControl ItemsSource="{Binding}" DisplayMemberPath="Header"/> 

代碼:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     this.DataContext = new List<TabItemModel> 
     { 
      new TabItemModel 
      { 
       Header = "First" 
      }, 
      new TabItemModel 
      { 
       Header = "Second" 
      }, 
     }; 
    } 
} 

public class TabItemModel 
{ 
    public string Header 
    { 
     get; 
     set; 
    } 
} 

結果:

enter image description here

所以,問題不在於TabControl.DisplayMemberPath不起作用 - 這是你的過於複雜的代碼中的其他地方。簡化,直到找到位置。

+0

我已經做了一些測試,發現如果您的項目繼承自「控制」,則會出現這些問題。 – Andre 2012-04-02 11:55:49

相關問題