按下按钮更改值时,绑定目标未更新

时间:2019-03-20 15:10:59

标签: c# wpf data-binding wpf-controls

我有一些使用表格的代码。该表格已绑定到我的班级FormData。我的绑定工作正常,并且更新了formData(本地实例),但是当我尝试在按钮click / LostFocus触发器上更改formData中变量之一的值时,它不会更新。

这是我相关的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;
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

您需要实现INotifyPropertyChanged接口并在PropertyChanged类中引发formData事件:

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));
    }
}

答案 1 :(得分:-1)

您的类需要实现INotifyPropertyChanged,以便目标知道源属性是否更改: https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-property-change-notification 这真的很容易,请查看文档并相应地调整代码。您的媒体资源必须如下所示:

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

但是您还需要事件和onPropertyChanged函数来使其正常工作。 祝您编码愉快!