c# - 如何知道所选选项卡的名称? (MVVM)

标签 c# wpf mvvm mvvm-light

我有一个控制按钮点击事件的 View 模型,代码是:

ucMantenimientoView miViewPlanificacion = new ucMantenimientoView();
ucMantenimientoViewModel miViewModelPlanificacion = new ucMantenimientoViewModel();
miViewPlanificacion.DataContext = miViewModelPlanificacion;

View 有一个选项卡,使用 MVVM Light 我管理选项卡控件的 selectedItem 事件的 View 模型上的点击事件。

问题是我需要知道在创建 View 和 View 模型时选择的选项卡的名称是哪个,但是 selectedItem 没有触发,默认情况下选择第一个选项卡,所以我不知道如何在创建 View 模型时获取所选选项卡的名称。

如果我选择了另一个选项卡,然后又选择了第一个选项卡,那么它就可以工作,但是我需要在 View 模型的构造函数中使用这些数据。

谢谢。

最佳答案

当使用 WPF 和 MVVM 并且我们想知道 UI 控件的某些值时,通常会将 View 模型属性简单地数据绑定(bind)到该 UI 属性。通过这种方式,我们始终可以在 View 模型中随时获得所需的数据。

如何设置 Binding 将取决于您设置 XAML 的方式。如果您像下面的示例那样数据绑定(bind) TabControl.ItemsSource,那么您将在 YourTabItemData.HeaderText 中获得所有 TabItem.Header 属性的文本 属性:

<TabControl ItemsSource="{Binding YourTabItemData}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding HeaderText}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <!-- Content -->
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

然后您可以将相关类型的对象数据绑定(bind)到 TabControl.SelectedItem 属性,然后您就可以访问 TabControl.Header 中的文本所选 TabItem:

<TabControl ItemsSource="{Binding YourTabItemData}" SelectedItem="{Binding YourItem}">
    ...
</TabControl>

...

public YourTabItemDataClass YourItem
{
    get { return yourItem; }
    set 
    {
        yourItem = value; 
        NotifyPropertyChanged(); 
        // Selected TabItem has just changed
        string headerOfSelectedTab = yourItem.HeaderText;
    }
}

但是,如果您没有将数据绑定(bind)到 TabControl.ItemsSource 属性,则有一个更简单的解决方案。您可以设置 SelectedValuePath 属性以从所选 TabItem 返回 Header 值,然后将数据绑定(bind)到 SelectedValue属性获取实际值:

<TabControl SelectedValue="{Binding Selected}" SelectedValuePath="Header">
    <TabItem Header="HeaderOne" Name="NameOne"></TabItem>
    <TabItem Header="HeaderTwo" Name="NameTwo"></TabItem>
</TabControl>

您甚至可以根据自己的需要使用这两种解决方案的一部分。

Disclaimer:
I just assumed that you meant Header when you said Name, but if you really meant Name, then this solution would work just as well if you simply replace all occurrences of Header with Name.

关于c# - 如何知道所选选项卡的名称? (MVVM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425385/

相关文章:

c# - Mysql 更新数据库 System.FormatException

c# - .NET Core Web API 无法正确读取环境

c# - 如何根据标题高度定位 WPF Expander?

c# - WPF 使用新参数重新加载页面

wpf - 如何将 View 中控件的 UI 调度程序传递给 ViewModel

c# - 使用多核(线程)处理器进行 FOR 循环

c# - 将属性属性设置为装饰类的类型

wpf - 单击模板中的按钮时如何选择 ListBoxItem?

c# - LayoutAwarePage 的 MVVM 够用吗?

c# - Silverlight + MVVM + 绑定(bind) = 内存泄漏?