我有一个控制按钮点击事件的 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 meantHeader
when you saidName
, but if you really meantName
, then this solution would work just as well if you simply replace all occurrences ofHeader
withName
.
关于c# - 如何知道所选选项卡的名称? (MVVM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425385/