简体   繁体   中英

Property changed event is not getting fired wpf

I have to change the value in a text box dynamically, on selecting a value from a combox box, which is present in different view. when changing the dependency property's source, the propertychangedEventHandler value is not changing, ie it is remaining as null, so the event is not getting fired. As a result the text in the textbox is not changing. Below is the code. I have bound the text in textbox to _name property.

public partial class Details : UserControl, INotifyPropertyChanged
{

   public event PropertyChangedEventHandler PropertyChanged;
   public string name = "";

     public Details()
     {
       InitializeComponent();
       Name = Connector.Name;
       DataContext = this;
     }


    public string Name
    {
       get { return name; }
       set
       {
           name = value; OnPropertyChanged("Name");
       }
   }

   protected void OnPropertyChanged(string s)
   {
         PropertyChangedEventHandler handler = PropertyChanged;
         if (handler != null)
         {
             handler(this, new PropertyChangedEventArgs(s));
         }
   }
}

Xaml code

    <StackPanel Orientation="Vertical">

            <TextBlock Text="Student Details" VerticalAlignment="Top" HorizontalAlignment="Center" FontSize="16" FontWeight="Bold">  </TextBlock>

            <StackPanel Margin="0,5" Orientation="Horizontal" >

        <Label MinWidth="100" MaxWidth="110">Name:</Label>

                <Border BorderBrush="Gray" BorderThickness="2">

                    <TextBox Name="nametextbox" Text="{Binding Name,Mode=TwoWay}"  Width="auto" MinWidth="100" FontWeight="Black"></TextBox>
                </Border>

            </StackPanel>

Is it possible that you accidentally exchanged name and _name , using name in XAML for the binding?

Usually you have a public property with a capitalized name, and a private field with a non-capitalized name, optionally prefixed with an underscore as you did.

So, you should have

public string Name {
    get { return _name; }
    set { _name = value; OnPropertyChanged("Name"); }
{

private string _name = "";

Please check the following:

  • If you're not currently binding to name instead of _name ;
  • Either if that is or is not the case, please fix your naming convention, because it is a source of errors, and every example you'll find follow the convention I included above.

In your XAML, you are binding "Name" property and in your code, you have created _name property. So, you need to change it to "Name" property in your code.

Just change your property as per below:

private string _name = "";

public string Name 
        {
    get { return _name; }
    set { 
         _name = value; 
         OnPropertyChanged("Name"); 
        }
}

Try this and let me know.

I have used eventaggregator for this purpose, as we need to change the text in the text box dynamically when an event in a different view is fired. Below is the C# code of both the DropView(where we select student name from a list), and DetailsView(where we display the details). I publish events in Drop.xaml.cs and subscribe to those events in Details.xaml.cs

Drop.xaml.cs

public partial class Drop : UserControl {

    private IEventAggregator iEventAggregator;

    public Drop(IEventAggregator ieventaggregator)
    {
        InitializeComponent();
        iEventAggregator = ieventaggregator;
        this.DataContext = this;
        var doc = XDocument.Load("C:\\Users\\srinivasaarudra.k\\Desktop\\students.xml");           
        var names = doc.Descendants("Name");
        foreach (var item in names)
        {
            droplist.Items.Add(item.Value);
        }

    }
    public string name;
    public string Naam
    {
        get { return name; }
        set { name = value;
        iEventAggregator.GetEvent<Itemselectedevent>().Publish(Naam);
        }

    }
    public string grade;
    public string Grade
    {
        get { return grade; }
        set
        {
            grade = value;
            iEventAggregator.GetEvent<gradeevent>().Publish(Grade);
        }
    }
    public string dept;
    public string Dept
    {
        get { return dept; }
        set
        {
            dept = value;
            iEventAggregator.GetEvent<deptevent>().Publish(Dept);
        }
    }
    public static string str;
    public static string Str
    {
        get { return str; }
        set {
            str = value;

             }
    }

    private void droplist_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      var sel = droplist.SelectedValue;
      Str=sel.ToString();
      XmlDocument doc2 = new XmlDocument();
      doc2.Load("C:\\Users\\srinivasaarudra.k\\Desktop\\students.xml");
      var details = doc2.DocumentElement.SelectNodes("/Students/StudentDetails");
      foreach (XmlNode node in details)
      {
          if (node.SelectSingleNode("Name").InnerText == Str)
          {
              Naam = node.SelectSingleNode("Name").InnerText;
              Grade = node.SelectSingleNode("Grade").InnerText;
              Dept = node.SelectSingleNode("Department").InnerText;

          }

      }
    //  Details det = new Details();  
      Details dt = new Details(iEventAggregator);

    }


}
 public class Itemselectedevent:Prism.Events.PubSubEvent<string>
    {

    }
 public class gradeevent : Prism.Events.PubSubEvent<string>
 {

 }
 public class deptevent : Prism.Events.PubSubEvent<string>
 {
 }

Details.xaml.cs

public partial class Details : UserControl,INotifyPropertyChanged {

    public IEventAggregator iEventAggregator;

   public  event PropertyChangedEventHandler PropertyChanged;

   public static string name;
   public static string dept;
   public static string grade;

   [Bindable(true)]
   public  string Naam
   {
       get { return name; }
       set
       { 
        name = value;
        OnPropertyChanged("Naam");
       }

   }
   [Bindable(true)]
   public string Grade
   {
       get { return grade; }
       set
       {

               grade = value; OnPropertyChanged("Grade");

       }
   }
   [Bindable(true)]
   public string Dept
   {
       get { return dept; }
       set
       {

               dept = value;
               OnPropertyChanged("Dept");

       }
   }
   public Details(IEventAggregator eventaggregator)
   {
       InitializeComponent();
       this.iEventAggregator = eventaggregator;
       iEventAggregator.GetEvent<Itemselectedevent>().Subscribe((str) => { Naam = str; });
       iEventAggregator.GetEvent<gradeevent>().Subscribe((str) => { Grade = str; });
       iEventAggregator.GetEvent<deptevent>().Subscribe((str) => { Dept = str; });          
       this.DataContext = this;           
   }

   protected void OnPropertyChanged(string s)
   {
         PropertyChangedEventHandler handler = PropertyChanged;          
         if (handler != null)
         {
             handler(this, new PropertyChangedEventArgs(s));
         }            
   }
   private void Button_Click_1(object sender, RoutedEventArgs e)
   {  
     Application.Current.Shutdown();
   }      
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM