从Child UserControl

时间:2017-10-12 00:02:48

标签: c# wpf xaml mvvm command

我有一个主窗口,里面有TabControl。每个标签都包含与其关联的UserControl。在我的一个UserControl中,我有一个按钮。当我点击该按钮时,我想更改主窗口中SelectedIndex的{​​{1}}。

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

例如:

TabControl

先谢谢我的同事们!

修改

窗口视图模型:

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

以下是选项卡中UserControl的代码:

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的XAML(位于TabControl中):

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
}

1 个答案:

答案 0 :(得分:0)

为子视图模型提供公共属性

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

将其绑定到usercontrol XAML中按钮的Command属性。

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

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

相关问题