简体   繁体   English

如何以编程方式移动到WPF TabControl中的下一个选项卡?

[英]How can I programmatically move to the next tab in a WPF TabControl?

I'm having a bit of trouble with this. 我对此有点麻烦。 I need to add code to move a TabControl to the next page. 我需要添加代码以将TabControl移至下一页。 I'm using System.Windows.Controls.TabControl available in .Net 4.5. 我正在使用.Net 4.5中提供的System.Windows.Controls.TabControl I'm not even sure how I can enumerate the TabPages . 我什至不知道如何枚举TabPages

An MVVM solution would be ideal, but I can work with a code behind solution. MVVM解决方案将是理想的选择,但是我可以使用解决方案背后的代码。 I'd change it a custom behavior or something. 我将其更改为自定义行为或其他内容。

Thanks. 谢谢。

You could implement INotifyPropertyChanged in your ViewModel, and then bind the SelectedIndex to an integer property in your ViewModel which notifies on change, something like this: 您可以在ViewModel中实现INotifyPropertyChanged,然后将SelectedIndex绑定到ViewModel中的一个整数属性,该属性会在更改时发出通知,如下所示:

ViewModel: ViewModel:

public sealed class MainViewModel : INotifyPropertyChanged
{
    private int _tabNumber = 0;

    public int TabNumber
    {
        get { return _tabNumber; }
        set
        {
            if (value == _tabNumber) return;
            _tabNumber = value;
            OnPropertyChanged("TabNumber");
        }
    }

    private void ChangeTab(int tabNumber)
    {
        TabNumber = tabNumber;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML: XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" DataContext="{StaticResource MainViewModel}">
    <Grid>
        <TabControl Height="100" SelectedIndex="{Binding TabNumber}" HorizontalAlignment="Left" Margin="108,108,0,0" Name="tabControl1" VerticalAlignment="Top" Width="200">
            <TabItem Header="tabItem1" Name="tabItem1">
                <Grid />
            </TabItem>
        </TabControl>
    </Grid>
</Window>

You can do this: 你可以这样做:

tabControl1.SelectedIndex++;

or can Bind it in XAML 或者可以将其绑定到XAML中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM