WPF:将TabControl SelectedIndex绑定到View Model的枚举属性

时间:2018-06-07 18:44:13

标签: c# wpf model-view-controller

我的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
}

我希望能够将我的TabControl的SelectedIndex(或SelectedItem)绑定到此属性,并使用转换器正确设置相应的选项卡。不幸的是,我有点卡住了。我知道我可以很容易地在我的模型中使用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导入我的转换器,所以我可以这样做:

// 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转换器没有太多运气。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我没有在XAML中指定值,而是将ItemsSource绑定到枚举中的值数组:

代码:

public AvailableTabs[] AvailableTabs => Enum.GetValues(typeof(AvailableTabs Enum)).Cast<AvailableTabs>().ToArray();

XAML:

<TabControl Name="MyTabControl" SelectedIndex="{Binding SelectedTab}" ItemsSource="{Binding AvailableTabs}" />

答案 1 :(得分:0)

您只需要一个将值转换为索引的转换器。

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;
    }
}