I want to notify Xaml of property changes in OnPropertyChanged

Asked 2 years ago, Updated 2 years ago, 38 views

I want to notify Xaml of a property change when the BlockColumnPosition1 property is changed, but PropertyChanged is null in the OnPropertyChanged method and is not notified.I think you'll be notified once you pass this if statement...
This is a rudimentary question, but please let me know.

public partial class MainWindow:Window,INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        GenerateBlock();
    }

    internal enum PropertyNames
    {
        BlockColumnPosition 1,
        BlockRowPosition 1,
    }


    /// <summary>
    /// Block Location (Column)
    /// </summary>
    private Int32 blockColumnPosition;

    /// <summary>
    /// Block position (row)
    /// </summary>
    private Int32 blockRowPosition;


    /// <summary>
    /// Gets and sets the block position (column).
    /// </summary>
    private Int32 BlockColumnPosition1
    {
        get
        {
            return this.blockColumnPosition;
        }
        set
        {
            This.blockColumnPosition=value;
            This.OnPropertyChanged(PropertyNames.BlockColumnPosition1.ToString());
        }
    }

    /// <summary>
    /// Gets and sets the block position (row).
    /// </summary>
    private Int32 BlockRowPosition1
    {
        get
        {
            return this.blockRowPosition;
        }
        set
        {
            This.blockRowPosition=value;
            This.OnPropertyChanged(PropertyNames.BlockRowPosition1.ToString());
        }
    }


    private void GenerateBlock()
    {
        BlockColumnPosition 1 = 5;
        BlockRowPosition 1 = 1;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged (String propertyName)
    {
        if (PropertyChanged!=null)
            PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
    }


}

c#

2022-09-30 21:27

1 Answers

First, INotifyPropertyChanged (in this case MainWindow) must be bound to the view.If you set this to DataContext, the question code uses PropertyChanged in principle.

Next, MainWindow inherits DependencyObject, so you should use the dependency property mechanism instead of INotifyPropertyChanged Enter Visual Studio to insert the model in 's C# editor.

Finally, if you want to bind to the MainWindow property within MainWindow, you can use RelativeSource.

If you want to get the property name string, you can easily refer to nameof(BlockColumnPosition1).In addition, [CallerMemberName] eliminates the need to specify a name.


2022-09-30 21:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.