【发布时间】:2021-07-22 03:24:18
【问题描述】:
当用户提交 TextBox 所属的表单时,我试图在输入验证期间使用视觉状态将 TextBox 输入标记为无效(通过将其边框颜色更改为红色)。我有以下代码:
XAML
<Page.Resources>
<!-- Other resources omitted for brevity -->
<Flyout x:Key="NewTimeBlockFlyout">
<StackPanel>
<!-- Other stuff here omitted for brevity -->
<TextBox Margin="5"
Header="Name"
x:Name="NewTimeBlockNameTextBox">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="Default"></VisualState>
<VisualState x:Name="Invalid">
<VisualState.Setters>
<Setter Target="NewTimeBlockNameTextBox.Background" Value="Red"></Setter>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</TextBox>
<!-- The rest of the form omitted for brevity -->
<Button x:Name="CreateTimeBlockButton"
Grid.Column="0"
Margin="0,0,2,0"
HorizontalAlignment="Stretch"
Tapped="CreateTimeBlockButton_Tapped">Create</Button>
</StackPanel>
</Flyout>
</Page.Resources>
注意:这是在 XAML Page 上。我没有使用自定义控件。
C#
private void CreateTimeBlockButton_Tapped(object sender, TappedRoutedEventArgs e)
{
// Validate the input.
if (String.IsNullOrWhiteSpace(this.NewTimeBlockNameTextBox.Text))
{
// These two lines of code confirm the visual state named "Invalid" does exist on the textbox.
//List<VisualStateGroup> m = VisualStateManager.GetVisualStateGroups(this.NewTimeBlockNameTextBox).ToList();
//List<VisualState> c = m.FirstOrDefault().States.ToList();
// Assignment to bool just used to inspect the return value for debugging.
bool did = VisualStateManager.GoToState(this.NewTimeBlockNameTextBox, "Invalid", false);
}
}
问题
无论我尝试什么,对 VisualStateManager.GoToState() 的调用总是返回 false。
我尝试过的事情:
这里是relevant documentation from Microsoft。
如上面的 C# 代码所示,我已经验证了视觉状态“无效”确实存在于“NewTimeBlockNameTextBox”控件上,正如预期的那样。
我见过几个解决方案,包括here 和here,它们建议将XAML 中的<VisualStateManager.VisualStateGroups> 标记移到TextBox 之外,或者移到Page 的根目录。两者都没有为我工作。
【问题讨论】:
标签: c# validation xaml uwp visualstatemanager