我有一个要求,即在加载新视图时专注于特定的文本框。将用户控件绑定到自定义BusyIndicator控件
的解决方案是这一行的代码添加到装载的事件的看法:
Dispatcher.BeginInvoke(() => { NameTextBox.Focus(); });
所以这个工作了一个观点,而不是其他。我花了一些时间调试问题,并意识到我正在处理的新视图有一个BusyIndicator,它将焦点从所有控件中移除,因为BusyIndicator在OnLoaded事件之后被设置为true和false。
所以解决的办法是在后将焦点调用到NameTextBox
我的BusyIndicator已被设置为false。我的想法是创建一个可重用的BusyIndicator控件来处理这些额外的工作。但是,我在MVVM中遇到了麻烦。
我开始制作工具的简单扩展:BusyIndicator控件:
public class EnhancedBusyIndicator : BusyIndicator
{
public UserControl ControlToFocusOn { get; set; }
private bool _remoteFocusIsEnabled = false;
public bool RemoteFocusIsEnabled
{
get
{
return _remoteFocusIsEnabled;
}
set
{
if (value == true)
EnableRemoteFocus();
}
}
private void EnableRemoteFocus()
{
if (ControlToFocusOn.IsNotNull())
Dispatcher.BeginInvoke(() => { ControlToFocusOn.Focus(); });
else
throw new InvalidOperationException("ControlToFocusOn has not been set.");
}
我加入了控制我的XAML文件,没有问题:
<my:EnhancedBusyIndicator
ControlToFocusOn="{Binding ElementName=NameTextBox}"
RemoteFocusIsEnabled="{Binding IsRemoteFocusEnabled}"
IsBusy="{Binding IsDetailsBusyIndicatorActive}"
...
>
...
<my:myTextBox (this extends TextBox)
x:Name="NameTextBox"
...
/>
...
</my:EnhancedBusyIndicator>
这样的想法是当IsRemoteFocusEnabled
是在我的ViewModel中设置为true(我在ViewModel中将IsBusy
设置为false后执行此操作),焦点将设置为NameTextBox
。如果它有效,其他人可以使用EnhancedBusyIndicator
,只需绑定到不同的控件,并在其自己的ViewModels中适当地启用焦点,前提是它们的视图具有初始的BusyIndicator
活动状态。
不过,我得到这个例外视图加载时:
设置属性“foo.Controls.EnhancedBusyIndicator.ControlToFocusOn”引发了异常。 [Line:45 Position:26]
我想尝试这个解决方案吗?如果是这样,到目前为止我有什么问题(不能设置ControlToFocusOn
属性)?
更新1
我安装了Visual Studio 10点的工具为Silverlight 5和导航到新视图时,有一个更好的错误消息。现在我格特此错误消息:
“System.ArgumentException:类型System.Windows.Data.Binding的对象不能转换为类型System.Windows.Controls.UserControl”
另外,我觉得我需要更改此控件的DataContext。在代码隐藏构造函数中,DataContext被设置为我的ViewModel。我尝试添加一个DataContext属性的EnhancedBusyIndicator
,但没有奏效:
<my:EnhancedBusyIndicator
DataContext="{Binding RelativeSource={RelativeSource Self}}"
ControlToFocusOn="{Binding ElementName=NameTextBox}"
RemoteFocusIsEnabled="{Binding IsRemoteFocusEnabled}"
IsBusy="{Binding IsDetailsBusyIndicatorActive}"
...
>
更新2
我需要改变UserControl
到Control
,因为我会希望将焦点设置到TextBox
对象(实现Control
)。但是,这并不能解决问题。
我实际上使用Silverlight 4;我只是通过使用适用于Silverlight 4的Visual Studio 10 Tools for Silverlight 5获得了更好的错误消息,该消息发布在“Update 1”中。我没有尝试将其作为静态资源进行绑定。我会试一试。 – 2012-01-16 19:48:45