Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# XAML WPF Binding
hi
 
I created a user control in wpf and set DependencyProperty
 
public partial class MyUserControl : UserControl
{
   public static readonly DependencyProperty DP = DependencyProperty.Register  ("Text", typeof(string), typeof(MyUserControl));
   public string Text
   {
      get
      {
         return this.MyTextBox.Text;
      }
      set
      {
         MyTextBox.Text = value;
      }
   }
   public MyUserControl()
   {
      InitializeComponent();
   }
}
 
the problem is I can not bind Text in my application:
 
<my:MyUserControl HorizontalAlignment="Left" Name="myUserControl" VerticalAlignment="Top" Width="74" Text="{Binding Path=UserName, Mode=TwoWay}"/>
Doesn't work
 
but it is ok for other controls and works:
<dxe:TextEdit HorizontalAlignment="Left" Name="textEdit1" VerticalAlignment="Top" Width="73" Text="{Binding Path=UserName, Mode=TwoWay}" />
 
Pleese help me i googled a lot
Posted 24-Apr-12 8:38am
Edited 24-Apr-12 12:03pm
v2
Comments
SAKryukov at 24-Apr-12 14:39pm
   
"Doesn't work" is not really informative.
--SA
V. Khachaturian at 24-Apr-12 14:49pm
   
just doesn't work. TextEdit shows UserName value but UserControl doesn't, i mean: "get { return this.MyTextBox.Text; } set { MyTextBox.Text = value; }" never execute and I don't know why?!!
Shahin Khorshidnia at 24-Apr-12 17:16pm
   
What is TextEditAutoComplete()?
I think it's the constructor! but why the name is defferent with the class?
V. Khachaturian at 24-Apr-12 18:04pm
   
yeah
it corrected
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Hello
 
My solution is not adequately standard but it works. I guess there is also a standard way that you can find Wink | ;)
 
But my solution:
 
public partial class MyUserControl: UserControl
{
   public readonly static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyUserControl), new PropertyMetadata(OnTextChanged));
 
   static void OnTextChanged(DependencyObject obj,
   DependencyPropertyChangedEventArgs args)
   {
      if (TextChanged != null)
         TextChanged(obj);
   }
 
   public delegate void TextChangeHandler(object sender);
   public static TextChangeHandler TextChanged;
 
   public string Text
   {
      get {return (String)this.GetValue(TextProperty);}
      set {this.SetValue(TextProperty, value);}
   }
   public MyUserControl()//Constructor
   {
      InitializeComponent();
      TextChanged += new TextChangeHandler((object sender) =>
      {
         //Prevent forcing changes to other instances of the user control
         if (this == ((MyUserControl)sender))
            this.MyTextBox.Text = this.Text;
      });
      
      this.MyTextBox.EditValueChanged += new EditValueChangedEventHandler((object sender, EditValueChangedEventArgs e) =>
      {
         this.Text = MyTextBox.Text;
      });
   }
}
 
And do not change the other things.
 
I hope it'll help!
  Permalink  
v2
Comments
V. Khachaturian at 24-Apr-12 18:01pm
   
thank you shahin solved my prob
Shahin Khorshidnia at 24-Apr-12 18:14pm
   
You're welcome :)
jiarline at 24-Apr-12 21:27pm
   
if ((object)this ==sender) this.MyTextBox.Text = this.Text; is better i prefer boxing to unboxing at the same situation.
SAKryukov at 25-Apr-12 16:41pm
   
My 5.
--SA
Shahin Khorshidnia at 25-Apr-12 16:52pm
   
Thank you very much SA :)
VJ Reddy at 25-Apr-12 20:28pm
   
Good answer. +5
Shahin Khorshidnia at 25-Apr-12 20:37pm
   
Thanks a lot VJ :)
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

As far as I know you shouldn't set/get value directly. Instead of this you should use GetValue/SetValue like this:
 
    get { return (String)this.GetValue(DP); }
    set { this.SetValue(DP, value); } 
  Permalink  
v2
Comments
V. Khachaturian at 24-Apr-12 14:57pm
   
Thank you, I try it and tell you soon the result
V. Khachaturian at 24-Apr-12 15:01pm
   
unfortunatly this doesn't work too
 
I mean: "get { return (String)this.GetValue(DP); }
set { this.SetValue(DP, value); }" doesn't execute at all.
Timur Akhmedov at 24-Apr-12 15:08pm
   
Set shouldn't be executed due to code optimizing. see here:
http://stackoverflow.com/questions/4225373/setters-not-run-on-dependency-properties
 
Try to debug your binding, like this:
add namespace
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"
 
then add Binding property:
Text="{Binding Path=UserName, Mode=TwoWay, diagnostics:PresentationTraceSources.TraceLevel=High}"
 
then check output window and tell us what do you see
V. Khachaturian at 24-Apr-12 15:11pm
   
Ok, but it still doesn't work. I mean when I change UserName (I implemented INotifyProrertyChanged) the text of TextEdit changes but the text of mycontrol doesn't change. and it is 2 way binding
Timur Akhmedov at 24-Apr-12 15:18pm
   
I just realized when you use DependencyProperty you don't need to use INotifyPropertyChanged interface. DependencyProperty track changes automatically. Show more of your code and Xaml
V. Khachaturian at 24-Apr-12 15:21pm
   
INotifyPropertyChange is for my Application and I used it to fire when UserName changes and it's not in my user Control.
Ok Thanks
V. Khachaturian at 24-Apr-12 15:17pm
   
and when I change my property to: "get { return (String)this.GetValue(DP); }
set { this.SetValue(DP, value); }"
Then how the user control understands that it should change MyTextBox.Text?!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Not sure what exactly you want to accomplish. In my WPF applications I always have my data defined in classes as follows:
   public class Mydata:INotifyPropertyChanged
   {
       private string userName;
       public string UserName
       {
           get { return userName; }
           set
           {   
                if ( userName != value )
                {
                      userName = value;
                      OnPropertyChanged(()=>this.UserName);
                }
           }
       }
       public void OnPropertyChange ( string propertyName )
        {
            if ( PropertyChanged != null )
                PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
        }
        public void OnPropertyChange<t> ( Expression<func><t>> propertyExpression )
        {
            OnPropertyChange( propertyExpression.Name );
        }
        public event PropertyChangedEventHandler PropertyChanged;
   }
</t></func></t>
 
Next in my codeBehind I have population code to expose this object as a public property:
 
      ....
      public Mydata SomeData = new SomeData();
      public MyUserControl()
      {
            Populate(SomeData);
      }
      ...
 
Finally in my binding :
 
<my:myusercontrol horizontalalignment="Left" name="myUserControl" verticalalignment="Top" width="74" text="{Binding Path=SomeData.UserName, Mode=TwoWay}" xmlns:my="#unknown" />
 
In WPF all bound properties MUST implement INotifyPropertyChanged and all collections must be encapsulated in ObservableCollection's.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 CPallini 365
1 Sergey Alexandrovich Kryukov 277
2 OriginalGriff 165
3 George Jonsson 159
4 Richard MacCutchan 110
0 OriginalGriff 6,344
1 Sergey Alexandrovich Kryukov 5,860
2 CPallini 5,125
3 George Jonsson 3,559
4 Gihan Liyanage 2,522


Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 24 Apr 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100