我在选项卡A上有文本框A,在选项卡B上有文本框B.我将它们数据绑定到同一属性。我使用相同的绑定:
<TextBox>
<TextBox.Text>
<Binding Path=ValueA UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:MyValidationRules />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
但是有一个问题。如果文本框A中的值无效,则不会更新源中的属性。但如果用户切换到选项卡b,它将会查找。基本上,验证规则阻止更新更改源。
我尝试将文本框b绑定到文本框a。问题是验证规则似乎只适用于文本框a,但不适用于b。
答案 0 :(得分:1)
设计明智,如果用户在文本框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);
}
}
}
希望这有帮助