【发布时间】:2013-12-16 04:12:44
【问题描述】:
我使用 Prism 和 MVVM 创建了一个基本应用程序。到目前为止,它仅由 Shell 和一个 View/ViewModel 组成。
在应用程序加载过程中,我将视图加载到我的主要区域,这会显示在屏幕上。这有效,但我无法让视图上的文本框聚焦。 看起来光标在框中(虽然它没有闪烁),但在我点击文本框之前它不接受文本输入。
我在一个新项目中重新创建了它,我所做的只是安装 prism/prism.unityextensions,设置 shell 和视图,并将视图加载到 shell 区域。这两个 xaml 文件的代码中都没有任何内容。
壳牌
<Window x:Class="MVVMFocusTest.Shell"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://www.codeplex.com/prism"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DockPanel LastChildFill="True">
<ContentControl Name="MainRegion" DockPanel.Dock="Top" prism:RegionManager.RegionName="MainRegion" />
</DockPanel>
</Grid>
</Window>
查看1
<UserControl x:Class="MVVMFocusTest.View1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
<Grid FocusManager.FocusedElement="{Binding ElementName=Username}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0">Username</Label>
<TextBox Name="Username" Grid.Row="0" Grid.Column="1" ToolTip="Enter Username" TabIndex="0" />
<Label Grid.Row="1" Grid.Column="0">Password</Label>
<PasswordBox Grid.Row="1" Grid.Column="1" Name="LoginPassword" PasswordChar="*" ToolTip="Enter Password" TabIndex="1" />
</Grid>
</StackPanel>
</UserControl>
谁能指出我做错了什么?据我所知,FocusManager.FocusedElement="{Binding ElementName=Username}" 应该足以设置焦点。
【问题讨论】:
-
我要做的是创建一个虚拟转换器并将其放置在绑定 FocusManager.FocusedElement="{Binding ElementName=Username , Path=. , Converter={StaticResource SomeDummyConverter}}" 现在放置一个断点在转换器的转换函数中并观察您的 TextBox 元素,它可能在您设置焦点时被禁用 (IsEnabled = False)。