【问题标题】:Bound target not updating when button pressed to change value按下按钮更改值时绑定目标不更新
【发布时间】:2019-03-20 15:10:59
【问题描述】:

我有一些使用表单的代码。该表格绑定到我的班级FormData。我的绑定运行良好并更新了我的formData(本地实例),但是当我尝试在按钮单击/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;
            }
        }
    }

【问题讨论】:

  • 你需要实现 INotifyPropertyChanged。

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


【解决方案1】:

您需要实现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));
    }
}

【讨论】:

  • 谢谢!我正在实现INotifyDataErrorInfo 接口,但没有意识到我需要INotifyPropertyChanged。现在效果很好。
【解决方案2】:

您的 Class 需要实现 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 函数才能使其工作。 快乐编码!

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多