2012-04-02 61 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

相关问题