【问题标题】:Change SelectedIndex of TabControl in MainWindow from Child UserControl从 Child UserControl 更改 MainWindow 中 TabControl 的 SelectedIndex
【发布时间】:2018-03-23 18:50:42
【问题描述】:

我有一个带有TabControl 的主窗口。每个选项卡都包含一个与之关联的UserControl。在我的UserControl 之一中,我有一个按钮。当我单击按钮时,我想更改主窗口中的TabControlSelectedIndex

我正在使用 MVVM 模式,所以如果可能的话,我想在 XAML 中使用按钮上的 Command 属性来实现。

例如:

<Button Content="Switch Tab" Command="SwitchTabCommand" />

提前感谢我的程序员伙伴!

编辑:

窗口视图模型:

public class CoolViewModel : BaseViewModel
{
    #region Properties

    public ObservableCollection<ITabViewModel> Tabs { get; set; }
    public ITabViewModel SelectedTab { get; set; }

    #endregion

    #region Constructor

    public CoolViewModel()
    {
        Tabs = new ObservableCollection<ITabViewModel>
        {
            new VeryNiceViewModel(),
            new VeryNiceViewModel()
        };
    }

    #endregion
}

这是标签内的 UserControl 的代码:

public class VeryCoolViewModel : BaseViewModel, ITabViewModel
{
    #region Properties

    public ObservableCollection<Test> Tests { get; set; }
    public Test currentSelection { get; set; }
    public string TabHeader { get; set; }

    #endregion

    #region Commands

    ICommand GoToOtherTab { get; set; }

    #endregion

    #region Constructor

    public GabaritSelecteurViewModel()
    {
        Tests = new ObservableCollection<Test>
        {
            new Test { Title = "Title #1" },
            new Test { Title = "Title #2" },
            new Test { Title = "Title #3" },
            new Test { Title = "Title #4" },
            new Test { Title = "Title #5" }
        };

        TabHeader = "Tests";

        GoToOtherTab = new RelayCommand(GoToTab, parameter => true);
    }

    #endregion

    #region Methods

    private void GoToTab(object parameter)
    {
        // I don't know how to tell to the
        // parent window to go to the other tab...
    }

    #endregion
}

这是 UserControl 的 XAML(位于 TabControl 内):

<Button Content="Go to the other tab" Command="{Binding GoToOtherTab}" />

【问题讨论】:

  • SelectedIndex 是一个 PITA。使用 SelectedItem 总是更容易(只要您的实例是 ItemsSource 集合中的一个)

标签: c# wpf xaml mvvm command


【解决方案1】:

给子视图模型一个公共属性

ICommand SwitchTabCommand { get {} set { /* INPC stuff */ } }

将其绑定到用户控件 XAML 中按钮的 Command 属性。

父视图模型可以在创建子视图模型时将命令分配给属性。您可以将父 vm 属性绑定到选项卡控件上的 SelectedIndex,并且父创建的命令可以设置绑定的父视图模型属性。

如果您不使用完整的 MVVM 并且用户控件没有子视图模型,请将命令属性设置为用户控件的依赖项属性,并将其绑定到窗口 XAML 中的父视图模型命令属性。

【讨论】:

  • 我试图做类似的事情,但我从来没有成功过。它总是告诉我 UserControl 或 Window 为空。我认为这是由它们的创建顺序引起的。
猜你喜欢
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2013-10-15
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2012-08-23
相关资源
最近更新 更多