1. 程式人生 > 實用技巧 >WPF 驗證表單方法3(彈窗)

WPF 驗證表單方法3(彈窗)

本文講述,當彈窗樣式固定,表單與提交按鈕不在同一個檔案下時,如何控制提交按鈕是否可用
比如自定義內容的彈窗就是這種情況
此時,我們希望無論自定義內容是什麼,它都可以控制彈窗Window的提交按鈕

效果如圖

這裡的內容和彈窗是分隔開的

該文章基於WPF 驗證表單方法1,在前文中講述的內容不再贅述

首先,在自定義內容UserControl中設定一個控制提交按鈕的屬性
這裡選擇在ViewModel中新增IsSubmitButtonEnable屬性

private bool isSubmitButtonEnable;

public bool IsSubmitButtonEnable
{
    get { return isSubmitButtonEnable; }
    set
    {
        if (isSubmitButtonEnable != value)
        {
            isSubmitButtonEnable = value;
            NotifyPropertyChanged(nameof(IsSubmitButtonEnable));
        }
    }
}

然後在彈窗生成的時候,檢測這個屬性,如果存在,則繫結提交按的IsEnabledProperty

Type t = control.DataContext.GetType();//獲得該類的Type
var property = t.GetProperties().Where(x => x.Name == nameof(ViewModelWithValidation.IsSubmitButtonEnable)).FirstOrDefault();
if (property != null)
{
    btnOK.DataContext = control.DataContext;
    btnOK.SetBinding(Button.IsEnabledProperty, new Binding(nameof(ViewModelWithValidation.IsSubmitButtonEnable))
    {
        Mode = BindingMode.OneWay,
        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
    });
}

最後在自定義內容中通過檢測輸入框,更新這個屬性即可

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    vm.ValidationInputs(new List<DependencyObject>()
    {
        nameTextBox,
        ageTextBox,
        remarkTextBox
    });
}

這裡沒有貼出所有的程式碼,如果有不明白的地方,可以先看WPF 驗證表單方法1,也可以直接看示例程式碼

示例程式碼

ValidationForm3