【发布时间】:2013-10-04 12:35:45
【问题描述】:
这是一个简单的屏幕,其中一个 textblock 最初是“”,一个 button 称为“设置文本”,它将文本设置为 textblock 和 another button,称为“清除文本”,它始终清除textblock 中的文本。这就是 XAML 的样子。
<StackPanel>
<TextBlock Text="{Binding DisplayText, Mode=TwoWay}"></TextBlock>
<Button Content="Set Text" Command="{Binding SetTextCommand}"></Button>
<Button Content="Clear Text" Command="{Binding CancelCommand}"
IsEnabled="{Binding CanCancel, Mode=TwoWay}"/>
</StackPanel>
这是我的 ViewModel 代码。
public class Page1VM : ViewModelBase
{
public RelayCommand SetTextCommand { get; private set; }
public RelayCommand CancelCommand { get; private set; }
public Page1VM()
{
SetTextCommand = new RelayCommand(HandleSetText, CanExecute);
CancelCommand = new RelayCommand(HandleClearButtonClick, CanExecuteCancel);
}
private void HandleSetText(string number)
{
DisplayText = number;
}
private string _displayText="";
public string DisplayText
{
get { return _displayText; }
set
{
_displayText = value;
RaisePropertyChanged("DisplayText");
RaisePropertyChanged("CanCancel");
}
}
private bool _canCancel;
public bool CanCancel
{
get
{
if (DisplayText == "")
{
return false;
}
else
{
return true;
}
}
set
{
_canCancel = value;
RaisePropertyChanged("CanCancel");
}
}
private bool CanExecute()
{
return true;
}
private bool CanExecuteCancel()
{
if (DisplayText == "")
{
return false;
}
else
{
return true;
}
}
private void HandleClearButtonClick()
{
DisplayText = "";
}
private void HandleSetText()
{
DisplayText = "Hello";
}
}
问题:加载页面时,“清除文本”按钮被禁用,这是预期的并且可以正常工作。
当我单击“设置文本”时,我通过将文本值设置为名为@987654328@ 的属性并将文本设置为文本块,并调用RaisePropertyChanged("CanCancel");,但即使在此之后我的“清除文本”按钮也未启用。背后的原因是什么?我的文本块显示文本值,但“明文”按钮仍未启用。
【问题讨论】:
-
您是在更改
DisplayText后尝试从命令中删除CanExecuteCancel还是尝试在CancelCommand上调用RaiseCanExecuteChanged()?问题是CanCancel,BTW 不需要设置器,因为它是只读的,不会刷新命令的CanExecute。
标签: c# windows-phone-7 mvvm windows-phone-8 mvvm-light