我開始因爲一些問題看這個我正在用組合框。不幸的是,我沒有解決我的問題,但我可以提供一些額外的見解和解決此問題的方法。首先,讓我開始對原始xaml進行更改。而不是創建從標籤控制到ComboBox的結合,並且反之亦然,我們可以將標籤和組合控制的selectedIndex之間建立一個雙向綁定(在這種情況下,默認)
<TabControl Height="100" Name="TabControl1" Width="220">
<TabItem Header="TabItem1" x:Name="TabItem1">
<TextBlock Text="TabItem1 Content" />
</TabItem>
<TabItem Header="TabItem2" x:Name="TabItem2">
<TextBlock Text="TabItem2 Content" />
</TabItem>
</TabControl>
<ComboBox Height="23" Name="CmbTabs" Width="120"
ItemsSource="{Binding ElementName=TabControl1, Path=Items}"
SelectedIndex="{Binding ElementName=TabControl1, Path=SelectedIndex}"
DisplayMemberPath="Name"
>
</ComboBox>
注意。接下來,我們添加一些內容到TabItems。在這一點上,類似於史蒂夫的建議,我們已經解決了「控制」問題。也就是說,更改選定的TabItem會更改選定的組合框項目(您必須信任此項或繼續閱讀!),並且更改組合框會更改所選的TabItem。大!
上述xaml還將DiplayMemberPath屬性更改爲「名稱」。我想你會發現這消除了hughdbrown的「怪異結果」。回想一下,ContentPresenter封裝了Header屬性(一個對象)。我相信,如果沒有提供模板,默認行爲是將Header對象顯示爲TextBlock中的字符串。因此,「奇怪的結果」正確地報告TextBlock控件不包含Header屬性。
現在讓我們對之前的ComboBox xaml進行一些更改。
<ComboBox Height="23" Name="CmbTabs" Width="120"
ItemsSource="{Binding ElementName=TabControl1, Path=Items}"
SelectedIndex="{Binding ElementName=TabControl1, Path=SelectedIndex}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
這實際上產生了一個有趣的結果,並利用我們添加到每個TabItem的內容。當此代碼運行時,您會注意到ComboBox現在顯示選定的TabItem的內容。此外,列表現在爲每個TabItem顯示「System.Windows.Controls.TabItem ...」。我們可以將TextBlock綁定更改爲{Binding Header}並顯示Header對象,但ComboBox仍然顯示所選TabItem的內容。由於週五晚上已經很晚了,世界上沒有足夠的啤酒,我沒有看到可能的原因。不過,我有一個解決方法!
首先,我們創建一個ValueConverter,將TabControl的Items集合轉換爲我們可以使用的東西。這是代碼。
public class TabItemCollectionConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
ItemCollection collection = value as ItemCollection;
IList<string> names = new List<string>();
foreach (TabItem ti in collection.SourceCollection)
{
names.Add(ti.Header.ToString());
}
return names;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
轉換器只需從TabControl的的項目集合,其中包含從每個TabItem的字符串,美化版標題對象創建一個新的集合。這對於簡單的Header對象工作正常,但顯然有侷限性。現在讓我們考慮一下我們如何在xaml中使用它。
<ComboBox Height="23" Name="CmbTabs" Width="120"
ItemsSource="{Binding ElementName=TabControl1, Path=Items, Converter={StaticResource ItemConverter}}"
SelectedIndex="{Binding ElementName=TabControl1, Path=SelectedIndex}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
請記住,在ItemsSource綁定中使用的ValueConverter會返回一個新集合。在這種情況下,我們將TabControl的Items集合轉換爲一個字符串集合。不要忘記創建轉換器StaticResource!它看起來像這樣。
<local:TabItemCollectionConverter x:Key="ItemConverter"/>
現在,使用轉換器,整個蠟球按預期工作。
讓我感到困惑的是,爲什麼ComboBox在列表中顯示TabItem標題,而TabItem的內容顯示爲選擇內容。毫無疑問,有一些明顯的解釋,但正如我所說,這是星期五...
希望這有助於!
你發現DisplayMemberPath =「Header」爲什麼不起作用嗎? – Coder14 2015-05-21 13:58:27