设计方面,如果用户在文本框 A 中输入了无效值,您不想在文本框 B 上显示它,因为它是无效的。如果我是你,我会拒绝用户访问选项卡 B,直到文本框 A 有效
这是一个例子:
看法:
<Grid>
<Grid.Resources>
<local:TabSelectionConverter x:Key="tabSelectionConverter"/>
</Grid.Resources>
<TabControl x:Name="myTabControl">
<TabItem x:Name="TabA" Header="Tab A">
<TextBox x:Name="TextBoxA" Text="{Binding MyTextProperty}" Height="20"/>
</TabItem>
<TabItem x:Name="TabB" Header="Tab B">
<TextBox x:Name="TextBoxB" Text="{Binding MyTextProperty}" Height="20"/>
</TabItem>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding TabSelectionChangedCommand}">
<i:InvokeCommandAction.CommandParameter>
<MultiBinding Converter="{StaticResource tabSelectionConverter}">
<Binding ElementName="myTabControl"/>
<Binding ElementName="TextBoxA" Path="Text"/>
</MultiBinding>
</i:InvokeCommandAction.CommandParameter>
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TabControl>
</Grid>
转换器将创建一个包含所有必要元素的对象,inroder 以验证拒绝访问第二个选项卡:
public class TabSelectionConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return new TabSelectionParameters
{
MainTab = values[0] as TabControl,
InputText = values[1] as string
};
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
public class TabSelectionParameters
{
public TabControl MainTab { get; set; }
public string InputText { get; set; }
}
以及您在 ViewModel 中的逻辑:
public class MainWindowViewModel : NotificationObject
{
private string myTextProperty;
public MainWindowViewModel()
{
TabSelectionChangedCommand = new DelegateCommand<TabSelectionParameters>(parameters =>
{
if (parameters.InputText == string.Empty) // Here goes the validation of the user input to TextBoxA
{
// Deny selection of tab B by returning the selection index to Tab A
parameters.MainTab.SelectedIndex = 0;
}
});
}
public DelegateCommand<TabSelectionParameters> TabSelectionChangedCommand { get; set; }
public string MyTextProperty
{
get
{
return myTextProperty;
}
set
{
myTextProperty = value;
RaisePropertyChanged(() => MyTextProperty);
}
}
}
希望这可以帮助