c# - 获取 View 模型中的选定选项卡(wpf)

标签 c# wpf mvvm tabs viewmodel

我有一个主视图,它有一个选项卡控件。选择选项卡时,它会调用适当的 View 进行显示。我在 View 模型中有一个函数,它必须知道选择了哪个选项卡来执行操作。我如何实现这一目标? View 模型如何知道选择了哪个选项卡?

最佳答案

很简单:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:TestViewModel x:Key="MainViewModel"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        <TabControl DataContext="{StaticResource MainViewModel}" 
                    SelectedIndex="{Binding Selected}" 
                    Grid.Row="0" 
                    x:Name="TestTabs">
            <TabItem Header="Section 1"/>
            <TabItem Header="Section 2"/>
            <TabItem Header="Section 3"/>
        </TabControl>
        <Button Content="Check 
                Selected Index" 
                Grid.Row="1" 
                x:Name="TestButton" 
                Click="TestButton_OnClick"/>
    </Grid>
</Window>

模型在这里以声明的方式定义为数据上下文。 selectedindex 属性绑定(bind)到模型,因此只要它发生变化,它在 View 模型上映射到的属性也会发生变化

class TestViewModel : INotifyPropertyChanged
{
    private int _selected;
    public int Selected
    {
        get { return _selected; }
        set
        {
            _selected = value;
            OnPropertyChanged("Selected");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

这实现了 INotifyPropertyChanged,因此 View 将向其注册。在这里的处理程序中,我输出 Selected 的值以在您更改它们时显示。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void TestButton_OnClick(object sender, RoutedEventArgs e)
    {
        var vm = TestTabs.DataContext as TestViewModel;
        MessageBox.Show(string.Format("You selected tab {0}", vm.Selected));
    }
}

这会获取 View 模型,然后向我们展示属性实际上已更新。

关于c# - 获取 View 模型中的选定选项卡(wpf),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263318/

相关文章:

c# - 从将其结果传递给 Action<T> 参数的方法返回 Task<T>

c# - 为什么要为每个类创建 Nlog Logger

c# - 在等待同一行代码时保持 UI 在主线程 webBrowser_DocumentCompleted 中响应

c# - datagrid 获取单元格索引

c# - 在后台代码中设置按钮样式

c# - 如何获取现有函数并在 C# 中使用 Func<..> 编写它?

wpf - 将样式应用于作为 StackPanel 子项的所有 TextBlock

MVVMCross iOS : How to trigger RowSelected on a Custom TableViewSource using CreateBindingSet?

mvvm - 如何在 ViewModel 中获取实际值并验证 CustomTextbox 文本

wpf - 在 View 中使用 DataTemplate 会在 View 和 ViewModel 之间创建耦合吗?