【发布时间】:2013-07-28 13:15:52
【问题描述】:
我的 XAML 中有一个 DataTrigger,它绑定到我的 ViewModel 类中的一个属性“ShowEffect”。我还有一个绑定到调用方法的RelayCommand(如下所示的类)的按钮。在该方法中,我将“ShowEffect”设置为 true。但是,DataTrigger 似乎没有回应;效果不显示:
我使用以下方式声明属性:
private Boolean _ShowEffect;
public Boolean ShowEffect
{
get { return _ShowEffect; }
set { _ShowEffect = value; }
}
RelayCommand班级:
public class RelayCommand : ICommand
{
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
}
我想知道问题是否与调度程序有关。当我在命令调用的方法中设置属性时,任何人都可以建议为什么绑定不起作用?当我在 ViewModel 中的任何其他位置设置属性时,它可以工作。
【问题讨论】:
-
你的虚拟机需要实现 INPC,如果它还没有实现,
ShowEffect需要在它被改变时引发 propertychanged 处理程序(从它的设置器当值改变),以便对其所做的更改被识别风景。你现在得到的是一个简单的属性,它不会通知视图对其所做的任何更新,这很可能是当命令更改它的值时发生的事情,但视图永远不会知道更改并且你的DataTrigger似乎不起作用. -
@Viv + 1 啊,谢谢。在属性设置器中添加
NotifyPropertyChanged("ShowEffect")解决了它!你想添加一个答案,以便我可以接受你是第一个吗? -
@Viv 刚刚编辑了之前的评论 :)
-
不客气 :) 并确实将其添加为答案。
标签: c# wpf data-binding mvvm command