那么如何使用 MVVM 模式将文本框聚焦在按钮单击上?
我基于this Answer创建了一个简单的Testproject ,它在第一次点击时起作用,但之后它不再设置焦点。我想念什么?
XAML(查看)
<Grid>
<TextBox Height='23' HorizontalAlignment='Left' Margin='12,12,0,0' VerticalAlignment='Top' Width='120'
Text='{Binding TheText}'
local:FocusExtension.IsFocused="{Binding IsFocused}"/>
<Button Content='Click' Height='23' HorizontalAlignment='Left' Margin='138,11,0,0' VerticalAlignment='Top' Width='75'
Command='{Binding ClickCommand}'/>
<Button Content='Just to deFocus' Height='28' HorizontalAlignment='Left' Margin='14,44,0,0' Name='button1' VerticalAlignment='Top' Width='199' />
</Grid>
视图模型
public class ViewModel : INotifyPropertyChanged
{
public string TheText { get; set; }
public bool IsFocused { get; set; }
private RelayCommand _clickCommand;
public ICommand ClickCommand
{
get { return _clickCommand ?? (_clickCommand = new RelayCommand(param => this.OnClick())); }
}
private void OnClick()
{
IsFocused = true;
RaisePropertyChanged("IsFocused");
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
#endregion
}
这是一个下载链接,其中包含一个可供懒惰者使用的项目(VS2010);)