我舉了一個例子來說明「正確的WPF方式」來解決這個場景。再次,它可能不符合你已有的代碼,但它應該給你一些關於如何調整你的代碼的想法。首先,代碼隱藏:
public partial class TabItemBinding : Window
{
public ObservableCollection<TextItem> Items { get; set; }
public TabItemBinding()
{
Items = new ObservableCollection<TextItem>();
Items.Add(new TextItem() { Header = "1", Content = new TextBox() { Text = "First item" } });
Items.Add(new TextItem() { Header = "2", Content = new TextBox() { Text = "Second item" } });
Items.Add(new TextItem() { Header = "3", Content = new TextBox() { Text = "Third item" } });
InitializeComponent();
}
}
public class TextItem
{
public string Header { get; set; }
public FrameworkElement Content { get; set; }
}
沒有什麼瘋狂的在這裏,我只是創建模型類,並建立該類的集合。真正的善良發生在XAML:
<Window x:Class="TestWpfApplication.TabItemBinding"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TabItemBinding" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ToolBar Grid.Row="0">
<Button Command="Undo">Undo</Button>
</ToolBar>
<TabControl Grid.Row="1" ItemsSource="{Binding Items}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Header}"/>
<Setter Property="Content" Value="{Binding Content}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
</Grid>
我勾了Button
到ApplicationCommands.Undo
,它會自動照顧撤銷對我們來說,只要我們有一個活動的編輯TextBox
。 TabControl
本身綁定到我們在代碼隱藏方面所做的集合,它將提供一個標題和一些文本進行編輯。我們所做的任何修改都是可撤銷的。其結果是:
Screenshot http://img706.imageshack.us/img706/2866/tabitembinding.png
順便說,需要注意的是,如果沒有一個活躍的編輯上下文撤銷命令會自動禁用本身是很重要的。所以如果沒有標籤頁,它將被禁用,沒有任何額外的代碼。
感謝嗨,這正是我需要的,但實際上我使用AvalonDock(http://avalondock.codeplex.com/)和「標籤」實際上文件。現在問題是我無法設置屬性來使它工作,如果我發佈我的代碼,你能幫我嗎? – Zviri 2010-06-03 17:15:00
是的,我一定會嘗試。但是,您應該先投票並接受我的答案,然後可能會在新問題中編寫AvalonDock代碼,因爲此處提出的問題已得到充分解答。 – Charlie 2010-06-03 17:30:15
如何將TabItem綁定到單選按鈕? – user2495173 2014-05-15 22:23:34