Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
hi
I created a user control in wpf and set DependencyProperty

C#
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:

XML
<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:
XML
<dxe:TextEdit HorizontalAlignment="Left" Name="textEdit1" VerticalAlignment="Top" Width="73" Text="{Binding Path=UserName, Mode=TwoWay}" />


Pleese help me i googled a lot
Posted
Updated 24-Apr-12 12:03pm
v2
Comments
Sergey Alexandrovich Kryukov 24-Apr-12 14:39pm    
"Doesn't work" is not really informative.
--SA
Vartan Khachatourian 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 24-Apr-12 17:16pm    
What is TextEditAutoComplete()?
I think it's the constructor! but why the name is defferent with the class?
Vartan Khachatourian 24-Apr-12 18:04pm    
yeah
it corrected

Hello

My solution is not adequately standard but it works. I guess there is also a standard way that you can find ;)

But my solution:

C#
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!
 
Share this answer
 
v2
Comments
Vartan Khachatourian 24-Apr-12 18:01pm    
thank you shahin solved my prob
Shahin Khorshidnia 24-Apr-12 18:14pm    
You're welcome :)
jiarline 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.
Sergey Alexandrovich Kryukov 25-Apr-12 16:41pm    
My 5.
--SA
Shahin Khorshidnia 25-Apr-12 16:52pm    
Thank you very much SA :)
As far as I know you shouldn't set/get value directly. Instead of this you should use GetValue/SetValue like this:

C#
get { return (String)this.GetValue(DP); }
set { this.SetValue(DP, value); }
 
Share this answer
 
v2
Comments
Vartan Khachatourian 24-Apr-12 14:57pm    
Thank you, I try it and tell you soon the result
Vartan Khachatourian 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.
TimGameDev 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
Vartan Khachatourian 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
TimGameDev 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
Not sure what exactly you want to accomplish. In my WPF applications I always have my data defined in classes as follows:
C#
   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:

C#
....
public Mydata SomeData = new SomeData();
public MyUserControl()
{
      Populate(SomeData);
}
...


Finally in my binding :

C#
<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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900