【发布时间】:2019-12-07 16:27:05
【问题描述】:
我正在尝试通过实现一个简单的按钮和文本框来学习 WPF。我想了解为什么我的按钮 IsEnabled 状态没有根据我的文本字段的值进行更新。
XAML:
<TextBox Height="100"
TextWrapping="Wrap"
Text="{Binding Test,NotifyOnSourceUpdated=True,NotifyOnTargetUpdated=True}"
VerticalAlignment="Top"
Padding="5, 3, 1, 1"
AcceptsReturn="True" Margin="161,10,10,0"/>
<Button Content="Go"
IsEnabled="{Binding MyButtonCanExecute}"
Command="{Binding MyButtomCommand}"
HorizontalAlignment="Left"
Margin="64,158,0,0"
VerticalAlignment="Top" Width="75"/>
C#:
class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public bool MyButtonCanExecute
{
get
{
return !String.IsNullOrWhiteSpace(Test);
}
}
private ICommand myButtonCommand;
public ICommand MyButtomCommand
{
get
{
if(myButtonCommand == null)
{
myButtonCommand = new RelayCommand(ShowMessage, param => this.MyButtonCanExecute);
}
return myButtonCommand;
}
}
private string test;
public string Test
{
get { return this.test; }
set
{
if (this.test != value)
{
this.test = value;
this.NotifyPropertyChanged("Test");
}
}
}
public MainWindowViewModel()
{
//
}
public void ShowMessage(object obj)
{
MessageBox.Show("Value of textbox is set to: " + this.Test);
}
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
问题:
当我在文本框中键入时,
Test设置器中的断点没有被命中。为什么?如果文本框绑定到Test属性,这不是重点吗?当我在文本框中输入时,
MyButtonCanExecute会不断被调用。但是,在调试中test的值始终为空……为什么?我在文本框中输入的内容不应该是什么吗?
主要问题似乎是Test 的值不会在我输入时更新。
我知道将IsEnabled 状态绑定到test 的长度可能有不同的方法,但我想了解我对 WPF 工作原理的理解有什么问题。
【问题讨论】:
-
“当我在文本框中键入时,我在测试设置器中的断点没有被命中”文本框不会立即更新 Text 属性的绑定,除非您设置 UpdateSourcetrigger=PropertyChanged - 默认情况下它是 LostFocus .单击按钮并调用 setter(假设 Window.DataContext 设置正确)
-
@ASh 谢谢,它现在在测试设置器中获得了价值。我在按钮的 IsEnabled 中添加了相同的 UpdateSourceTrigger,但输入后仍然无法启用?编辑:没关系,我自己修好了。将在下面添加答案并提及您。
-
IsEnabled 绑定到 MyButtonCanExecute,它不会在更改时通知。
this.NotifyPropertyChanged("Test"); this.NotifyPropertyChanged("MyButtonCanExecute");- 这将是解决这个问题。但是:通常你不绑定 IsEnabled。 IsEabled 是基于绑定命令的 CanExecute() 设置的 - ICommand 有一个事件来通知何时应该重新评估 CanExecute(以及下一个 IsEnabled) -
是的,谢谢,设法弄清楚这一点。我已经发布了一个答案,以防其他人将来遇到同样的问题。感谢您的帮助。