我的 ViewModel 上有一個枚舉屬性:視圖模型:public MyViewModel { // Assume this is a DependancyProperty public AvailableTabs SelectedTab { get; set; } // Other bound properties public string Property1 { get; set; } public string Property2 { get; set; } public string Property3 { get; set; }}public enum AvailableTabs { Tab1, Tab2, Tab3}我希望能夠?qū)?TabControl 的 SelectedIndex(或 SelectedItem)綁定到此屬性,并使用轉(zhuǎn)換器正確設(shè)置適當(dāng)?shù)倪x項卡。不幸的是,我有點卡住了。我知道我可以輕松地在我的模型中使用 SelectedIndex,但我想要重新排序選項卡而不破壞任何東西的靈活性。我給每個 TabItem 一個適用枚舉值的 Tag 屬性。我的 XAML:<TabControl Name="MyTabControl" SelectedIndex="{Binding SelectedTab, Converter={StaticResource SomeConverter}}"> <TabItem Header="Tab 1" Tag="{x:Static local:AvailableTabs.Tab1}"> <TextBlock Text="{Binding Property1}" /> </TabItem> <TabItem Header="Tab 2" Tag="{x:Static local:AvailableTabs.Tab2}"> <TextBlock Text="{Binding Property2}" /> </TabItem> <TabItem Header="Tab 3" Tag="{x:Static local:AvailableTabs.Tab3}"> <TextBlock Text="{Binding Property3}" /> </TabItem></TabControl>我的問題是我不知道如何將 TabControl 放入我的轉(zhuǎn)換器中,所以我可以這樣做:// Set the SelectedIndex via the enum (Convert)var selectedIndex = MyTabControl.Items.IndexOf(MyTabControl.Items.OfType<TabItem>().Single(t => (AvailableTabs) t.Tag == enumValue));// Get the enum from the SelectedIndex (ConvertBack)var enumValue = (AvailableTabs)((TabItem)MyTabControl.Items[selectedIndex]).Tag;恐怕我多慮了。我嘗試使用 MultiValue 轉(zhuǎn)換器,但運氣不佳。有任何想法嗎?
2 回答

繁星點點滴滴
TA貢獻1803條經(jīng)驗 獲得超3個贊
我不會在 XAML 中指定值,而是將 ItemsSource 綁定到枚舉中的值數(shù)組:
代碼:
public AvailableTabs[] AvailableTabs => Enum.GetValues(typeof(AvailableTabs Enum)).Cast<AvailableTabs>().ToArray();
XAML:
<TabControl Name="MyTabControl" SelectedIndex="{Binding SelectedTab}" ItemsSource="{Binding AvailableTabs}" />

子衿沉夜
TA貢獻1828條經(jīng)驗 獲得超3個贊
您只需要一個將值轉(zhuǎn)換為索引的轉(zhuǎn)換器。
public class TabConverter : IValueConverter
{
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
return (int)value;
}
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
return (AvailableTabs)value;
}
}
- 2 回答
- 0 關(guān)注
- 588 瀏覽
添加回答
舉報
0/150
提交
取消