【发布时间】:2014-09-13 23:03:02
【问题描述】:
我有一个非常简单的应用程序,其中包含 TextBox 和 Button。当TextBox 中输入的文本长度超过 5 个字符时,将启用该按钮。这是我的 ViewModel 的代码:
private string _text { get; set; }
public string Text
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged("Text");
}
}
private ICommand _buttonCommand;
public ICommand ButtonCommand
{
get
{
if (_buttonCommand == null)
{
_buttonCommand = new RelayCommand(
param => this.ButtonCommandExecute(),
param => this.ButtonCommandCanExecute()
);
}
return _buttonCommand;
}
}
private bool ButtonCommandCanExecute()
{
if (this.Text.Length < 5)
{
return false;
}
else
{
return true;
}
}
private void ButtonCommandExecute()
{
this.Text = "Text changed";
}
public MainWindowViewModel()
{
//
}
TextBox 和 Button 使用此 XAML 绑定:
<Button Content="Button" HorizontalAlignment="Left"
Margin="185,132,0,0" VerticalAlignment="Top" Width="120"
Command="{Binding Path=ButtonCommand}" />
<TextBox HorizontalAlignment="Left" Height="23"
Margin="185,109,0,0" TextWrapping="Wrap"
Text="{Binding Path=Text, Mode=TwoWay}" VerticalAlignment="Top" Width="120"/>
DataContext 似乎设置正确,但这里只是因为我是 WPF 初学者:
private MainWindowViewModel view_model;
public MainWindow()
{
InitializeComponent();
view_model = new MainWindowViewModel();
this.DataContext = view_model;
}
当我输入TextBox 时,Button 永远不会启用。
【问题讨论】:
-
如果您跳出 TextBox,它是否正确启用/禁用?
TextBox.Text的默认绑定模式是OnLostFocus,因此在TextBox失去焦点之前,数据不会保留回您的 VM。要更改它,您可以将绑定Mode属性设置为PropertyChanged。另外,您使用的是什么类型的 RelayCommand?如果是 MVVM 轻型中继命令,那么它应该在属性更改时自动引发CanExecuteChanged并重新查询CanExecute,但并非所有中继命令都是这样。 -
这也是一个问题,非常感谢 Rachel。
标签: c# wpf relaycommand