UpdateSourceTrigger =明确

Chr*_*urn 12 wpf binding

我正在创建一个带有多个文本框的WPF窗口,当用户按下OK按钮时,我希望所有文本框都被评估为非空白.我知道我必须使用TextBoxes和'Explicit'的'UpdateSourceTrigger',但我是否需要为每个人调用'UpdateSource()'?例如

<TextBox Height="23" 
     HorizontalAlignment="Left" 
     Margin="206,108,0,0" 
     Text="{Binding Path=Definition, UpdateSourceTrigger=Explicit}"
     Name="tbDefinitionFolder" 
     VerticalAlignment="Top" 
     Width="120" />

<TextBox Height="23" 
     HorizontalAlignment="Left" 
     Margin="206,108,0,0" 
     Text="{Binding Path=Release, UpdateSourceTrigger=Explicit}"
     Name="tbReleaseFolder" 
     VerticalAlignment="Top" 
     Width="120" />
Run Code Online (Sandbox Code Playgroud)

...

BindingExpression be = tbDefinitionFolder.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
BindingExpression be2 = tbReleaseFolder.GetBindingExpression(TextBox.TextProperty);
be2.UpdateSource();
Run Code Online (Sandbox Code Playgroud)

H.B*_*.B. 5

如果你使用,Explicit你需要打电话UpdateSource.

我不确定这是否是你尝试做的最好的方法,我实际上永远不会使用Explicit,我宁愿绑定到对象的副本,如果我不想立即应用更改,或者我存储副本如果要取消编辑,请将所有内容还原.


Gay*_*Fow 5

另一种方法是将UpdateSourceTrigger设置为PropertyChanged。

然后从INotifyPropertyChanged和IDataErrorInfo继承您的VM。这是一个例子

public class MyViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private string myVar;
    public string MyProperty
    {
        [DebuggerStepThrough]
        get { return myVar; }
        [DebuggerStepThrough]
        set
        {
            if (value != myVar)
            {
                myVar = value;
                OnPropertyChanged("MyProperty");
            }
        }
    }
    private void OnPropertyChanged(string prop)
    {
        if(PropertyChanged!=null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(pro));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public string Error
    {
        get { return String.Empty; }
    }
    public string this[string columnName]
    {
        get
        {
            if (columnName == "MyProperty")
            {
                if (String.IsNullOrEmpty(MyProperty))
                {
                    return "Should not be blank";
                }
            }
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

假设您的文本框之一绑定到了上面声明的“ MyProperty”。索引器在IDataErrorInfo中实现,并且在“ MyProperty”更改时被调用。在索引器主体中,您可以检查该值是否为空并返回错误字符串。如果错误字符串为非null,则用户会在TextBox上获得漂亮的装饰物作为视觉提示。因此,您可以轻松执行验证并提供UI体验。

如果您使用上面编码的两个接口并使用UpdateSourceTrigger = PropertyChanged,则所有这些都是免费的。UpdateSourceTrigger = Explicit的使用对于提供您描述的验证是过大的。

文本框的Xaml是...

 <TextBox DataContext="{StaticResource Vm}" Text="{Binding MyProperty,
                UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, 
                NotifyOnSourceUpdated=True, Mode=TwoWay}" Width="200" Height="25"/>
Run Code Online (Sandbox Code Playgroud)