0

I have a user control with the following elements

<Grid>
    <StackPanel Orientation="Horizontal" Width="150" Height="150">
        <TextBlock Text="hai"> </TextBlock>
        <TextBox Text="{Binding DeviceName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
        <TextBlock Text="{Binding DeviceID, Mode=TwoWay}"></TextBlock>
        <TextBlock Text="{Binding Test, Mode=TwoWay}"></TextBlock>
    </StackPanel>
</Grid>

I am setting the DataContext like below

 public partial class WorkFlowManager : UserControl
{
    public WorkFlowManager()
    {
        InitializeComponent();
        this.DataContext = new WorkFlowManagerVM();
    }
}

And my WorkflowManagerVM implements INotifyPropertyChanged

public class WorkFlowManagerVM : INotifyPropertyChanged

 public event PropertyChangedEventHandler PropertyChanged;

    public void RisePropertyChanged(string PropertyName)
    {
       if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
    }

The Propertchanged event is always null. Is there any problem the way I set the DataContext. This User control will be inside MainWindow. Not sure what has gone wrong.

  • User control doesn't have to have his own datacontext – Pavel Anikhouski Jan 10 '20 at 09:14
  • As a note, `Mode=TwoWay` on the Text Binding of a TextBlock is pointless. – Clemens Jan 10 '20 at 09:14
  • I'd even say a UserControl *must not* have its own view model. It should instead operate on a view model that is provided by its parent element, i.e. a Window or Page. – Clemens Jan 10 '20 at 09:16
  • How do you know that the PropertyChanged event of this private view model instance is null? How do you access it? I.e. how do you set one of its properties that would call RisePropertyChanged? I'd bet you are looking at some other instance of the view model class, i.e. not this private one. – Clemens Jan 10 '20 at 09:18
  • i am setting one of its property in different viewmodel. And i carete new instance for that. Both are two different instances then? – user12687752 Jan 10 '20 at 09:28
  • Sure. This is exactly the reason why a UserControl must not have its own view model. Simply remove `this.DataContext = new WorkFlowManagerVM();` – Clemens Jan 10 '20 at 09:33

0 Answers0