WPF UserControl Page Binding Issue

isa turgut 20 Reputation points
2024-11-16T21:04:03.78+00:00

Hello everybody,
I have a really basic question actually about WPF binding in my code. The problem is that I have a WPF page which inherited from a base class which inherits from UserControl and the base class implements INotifyPropertyChanged interface.

So that in my child class which is a page, I declare props and these props calling OnPropertyChanged method. Then I expect that after I bind the prop to the UI control then after the prop changed then it should update the UI side, but when I debug the code then the prop changed, PropertyChanged event comes null.

When I bind the prop in UI side I use ElementName= CodeBehind which the name of xaml, Path= propName, Mode=TwoWay,

By the way, the problem occurs only one project of mine, I mean, in the other project which is the same structure, it does not occur.

What is the problem of occuring that problem in WPF? Some of my research is saying that xaml does not find the props context, so that I call the code which is this.Context = this, but it does not work. What is the reason?

Developer technologies | Windows Presentation Foundation
Developer technologies | .NET | Other
{count} votes

Answer accepted by question author
  1. Anonymous
    2024-11-20T02:32:00.21+00:00

    Hi,@isa turgut.

    You used <local:BasePage> in UserControl1, you could directly set the DataContext for <local:BasePage>.

    UserControl1.xaml

    <local:BasePage x:Name="MyBasePage">
      ...
      <TextBlock x:Uid="txtBlock" 
               Text="{Binding Path=MyProperty, Mode=TwoWay}"
               FontSize="50"
               FontWeight="ExtraBold"></TextBlock>
      ...
    </local:BasePage>
    

    UserControl1.xaml.cs

    public UserControl1()
    {
        InitializeComponent();
        MyBasePage.DataContext = this;
        this.Loaded += UserControl1_Loaded;
    }
    

    The result of clicking the button:

    Screenshot 2024-11-20 022941


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.