C# 在UserControl中获取TabItem名称
我有以下创建TabControl的代码。每个选项卡都包含一个UserControl(代码如下),用于显示不同的数据(一个显示本地税务信息,另一个显示联邦/州税务信息) TabControlC# 在UserControl中获取TabItem名称,c#,wpf,tabcontrol,relaycommand,commandparameter,C#,Wpf,Tabcontrol,Relaycommand,Commandparameter,我有以下创建TabControl的代码。每个选项卡都包含一个UserControl(代码如下),用于显示不同的数据(一个显示本地税务信息,另一个显示联邦/州税务信息) TabControl 用户控制(TaxCodeMappingFooter) UserControl(TaxCodeMappingFooter)包含一个Add按钮,我需要通过RelayCommand将其连接到VM。我需要以某种方式告诉VM哪个选项卡正在调用Add命令,以便可以将项添加到正确的集合中。我想发送TabName,
用户控制(TaxCodeMappingFooter)
UserControl(TaxCodeMappingFooter)包含一个Add按钮,我需要通过RelayCommand将其连接到VM。我需要以某种方式告诉VM哪个选项卡正在调用Add命令,以便可以将项添加到正确的集合中。我想发送TabName,然后键入它,以知道用户在哪个选项卡上
我的想法是正确的还是更好的方法?如果是正确的,我如何获取TabName值以将其作为CommandParameter传递回?如果您要像以前那样硬编码UI控件,那么,您最简单的选择可能是在
TaxCodeMappingFooter
控件中定义字符串dependencProperty
:
public static readonly DependencyProperty TabNameProperty = DependencyProperty.
Register("TabName", typeof(string), typeof(TaxCodeMappingFooter));
public string TabName
{
get { return (string)GetTabName(TabNameProperty); }
set { SetTabName(TabNameProperty, value); }
}
然后您可以从选项卡项设置它:
<local:TaxCodeMappingFooter TabName="FedStateTaxesTab" DataContext="{Binding
RelativeSource={RelativeSource AncestorType=UserControl}}" />
正如其他人所说,如果您对视图模型结构进行了适当的建模,这将不是什么大问题
如果您确实想针对祖先元素进行绑定,可以使用FindAncestor
的RelativeSource
,然后指定AncestorType
。请注意,如果您是多个TabItem
的后代,则可能需要调整AncestorLevel
{Binding Path=Name
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type TabItem}}}
(为了清晰起见添加了包装)如果您正在使用MVVM,那么我会说更好的方法是每个选项卡都是一个视图/视图模型。你弄错了。对于MVVM,您应该为选项卡使用ViewModels,而不是硬编码的选项卡。在这种情况下,您可以访问当前选定的项目。
<local:TaxCodeMappingFooter TabName="FedStateTaxesTab" DataContext="{Binding
RelativeSource={RelativeSource AncestorType=UserControl}}" />
<Button Name="AddButton" Command="{Binding Path=DataContext.AddClickCommand}"
CommandParameter="{Binding TabName, RelativeSource={RelativeSource
AncestorType=TaxCodeMappingFooter}}" ... />
{Binding Path=Name
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type TabItem}}}