【发布时间】:2021-05-12 00:46:05
【问题描述】:
WPF 和 MVVM 的全新功能。我的应用程序有一个用于浏览文件的按钮和一个用于对所选文件执行任务的开始按钮。如果用户使用浏览按钮选择了文件,我只希望用户可以使用开始按钮。我使用 ViewModel 中的文件路径属性作为 CommandParameter 但这不起作用。任何帮助表示赞赏。
XAML
<Button Grid.Column="1" Grid.Row="2" Content="Browse File" Margin="0,0,5,5" Command="{Binding Path=CommandBrowseFile}" ></Button>
<Button Grid.Column="1" Grid.Row="3" Grid.ColumnSpan="2" Content="Start" Margin="0,0,0,5" Command="{Binding Path=CommandStart}" CommandParameter="{Binding Path=FilePath}"></Button>
视图模型
public class MyViewModel : ViewModelBase
{
public RelayCommand CommandBrowseFile { get; private set; }
public RelayCommand CommandStart { get; private set; }
private string _filePath;
public MyViewModel()
{
//L5XPath = "test";
CommandBrowseFile = new RelayCommand(BrowseFile);
CommandStart = new RelayCommand(Start, CanStart);
}
public string FilePath
{
get { return _filePath; }
set
{
_filePath = value;
}
}
public void BrowseFile(object message)
{
// Configure open file dialog box
OpenFileDialog dlg = new OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".l5x"; // Default file extension
dlg.Filter = "l5x files (.l5x)|*.l5x"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
FilePath = result == true ? dlg.FileName : null;
}
public void Start(object message)
{
//Do something
}
public bool CanStart(object message)
{
return message != null ? true : false;
}
}
中继命令
public class RelayCommand : ICommand
{
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new NullReferenceException("execute");
}
else
{
_execute = execute;
_canExecute = canExecute;
}
}
//public void RaiseCanExecuteChanged()
//{
// if (CanExecuteChanged != null)
// CanExecuteChanged(this, new EventArgs());
//}
public RelayCommand(Action<object> execute) : this(execute, null)
{
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute.Invoke(parameter);
}
}
【问题讨论】:
-
您没有正确实现绑定。查看重复项。
标签: c# wpf data-binding