当按下按钮以更改值时,绑定目标不更新



我有一些使用表单的代码。表格与我的课程绑定,FormData。我的绑定良好并更新了formData(本地实例),但是当我尝试更改formData中的一个变量的值时,请单击/LostFocus触发,它不会更新。

这是我的相关XAML:

<TextBox x:Name="friendly_name_textBox" 
                     Style="{StaticResource TextErrorStyle}"
                     Text="{Binding 
                PrimaryUserName,
                Mode=TwoWay,
                ValidatesOnExceptions=True,
                ValidatesOnDataErrors=True,
                UpdateSourceTrigger=PropertyChanged,
                NotifyOnValidationError=True}"
                     HorizontalAlignment="Left" 
                     Margin="0,75,0,0" 
                     TextWrapping="Wrap" 
                     VerticalAlignment="Top" 
                     Width="120"/>`

按钮触发器(确实运行):

private void Button_Click(object sender, RoutedEventArgs e)
    {
        formData.PrimaryUserName = "TEST";
    }

和我的FormData代码:

public string PrimaryUserName
    {
        get
        {
            return primaryUserNameValue;
        }
        set
        {
            if(primaryUserNameValue != value)
            {
                primaryUserNameValue = value;
            }
        }
    }

您需要实现InotifyPropertychanged接口并在formData类中提高PropertyChanged事件:

public class formData : INotifyPropertyChanged
{
    private string primaryUserNameValue;
    public string PrimaryUserName
    {
        get
        {
            return primaryUserNameValue;
        }
        set
        {
            if (primaryUserNameValue != value)
            {
                primaryUserNameValue = value;
                NotifyPropertyChanged();
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

您的类需要实现InotifyPropertyChanged,以便目标知道源属性是否更改:https://learn.microsoft.com/en-us/dotnet/framework/wpf/wpf/data/how-to-to-implement-property-change-notification这真的很容易,请查看文档并相应地调整您的代码。您的财产必须看起来像这样:

public string PrimaryUserName
{
    get
    {
        return primaryUserNameValue;
    }
    set
    {
        if(primaryUserNameValue != value)
        {
            primaryUserNameValue = value;
            OnPropertyChanged("PrimaryUserName");
        }
    }
}

,但是您还需要该事件和OnProperTychanged功能才能使其正常工作。快乐编码!

最新更新