給定的是一個帶有重置按鈕和文本框的 Wpf .Net5.0 應用程式
將設定路徑重置為默認值
Command="{Binding ResetCommand}" ... FilePath = @"C:\Temp";文本框:用戶可以編輯路徑
Text="{Binding FilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"private string _filePath; public string FilePath { get => _filePath; set { var r = new Regex(@"[\w\s\\.:\-!~]"); if (r.Matches(value).Count == value.Length) { SetProperty(ref _filePath, value); return; } throw new ArgumentException("Not an valid windows path"); } }
當路徑有效時,我可以重置為默認值。UI 更新 當用戶輸入無效字符時,邊框會變為紅色并且“重置”按鈕不會更新 UI。
我嘗試通過 Snoop 進行除錯,看起來虛擬機正在重置。但不是用戶界面。怎么了?
作業演示:https : //github.com/LwServices/WpfValidationDemo/tree/master/ValidationWpf
uj5u.com熱心網友回復:
簡單的解決方案
您可以通過設定值后直接通知您的UI來解決它
private void Reset()
{
FilePath = @"C:\Temp";
OnPropertyChanged(nameof(FilePath));
}
問題的原因
當Filepath與您的正則運算式不匹配時,您只需在不修改值的情況下引發例外_filePath,它將始終是有效路徑
public string FilePath
{
get => _filePath;
set
{
var r = new Regex(@"[\w\s\\.:\-!~]");
if (r.Matches(value).Count == value.Length)
{
SetProperty(ref _filePath, value); //<<<<<< this will never call if the value passed from the ui doesnot match Regex
return;
}
throw new ArgumentException("Not an valid windows path");
}
}
當您打電話時,reset()您嘗試設定Filepath為c:/temp ,如果最后一個值_filePath等于c:/temp,則問題將出現在以下內容中
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false; /// your code will return
field = value;
OnPropertyChanged(propertyName); // before notify the UI
return true;
}
因此,正如開頭所建議的,簡單的解決方案是直接通知您的 UI或從SetProperty方法中洗掉檢查行
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
uj5u.com熱心網友回復:
由于缺少 CanExecute 方法而禁用,請使用以下代碼
internal class MainWindowViewModel : NotifyPropertyChanged {
private DelegateCommand _resetCmd;
public ICommand ResetCommand => _resetCmd ?? new DelegateCommand(Reset, canRest);
private string _filePath;
public string FilePath
{
get => _filePath;
set
{
var r = new Regex(@"[\w\s\\.:\-!~]");
if (r.Matches(value).Count == value.Length)
{
SetProperty(ref _filePath, value);
return;
}
throw new ArgumentException("Not an valid windows path");
}
}
public MainWindowViewModel()
{
}
private void Reset(object obj)
{
FilePath = @"C:\Temp";
}
private bool canRest() {
return true;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/313597.html
上一篇:DbExpressionBinding需要輸入運算式LINQ
下一篇:標準輸出不列印每一行的日期和時間
