I am in a very basic problem.
I have created a user control, say sample like this :
<UserControl x:Class="TextCalc.txtItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<TextBox Name="txtMessage" Text="{Binding Message, ElementName=root}" Width="30" Height="20"></TextBox>
</Grid>
</UserControl>
I have created a
DependencyProperty
named
Message
which I want to work with DataBinding. The Code looks like :
public partial class txtItem : UserControl
{
public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message",typeof(String),typeof(txtItem), new UIPropertyMetadata("0", textChangedCallback));
private static void textChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
txtItem input = (txtItem)d;
input.txtMessage.Text = e.NewValue as String;
}
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
}
Now once I built the control, I want this control to work with Databinding just like how normal TextBox works. In my Window, I used this as :
<ListBox x:Name="lstBox" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<local:txtItem HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Message="{Binding Value}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
From the codebehind :
private List<Element> items = null;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.items = new List<Element>();
items.Add(new Element { Name = "Abhishek", Value = "300" });
this.lstBox.DataContext = items;
}
The Element class is also implemented from INotifyPropertyChanged :
public class Element : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get
{
return this._Name;
}
set
{
this._Name = value;
this.OnPropertyChanged("Name");
}
}
private string _Value;
public string Value
{
get
{
return this._Value;
}
set
{
this._Value = value;
this.OnPropertyChanged("Value");
}
}
#region INotifyPropertyChanged Members
public virtual void OnPropertyChanged(string info)
{
if(this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(info));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
Now when I change the data within the
Textbox
that comes within the
UserControl
, it doesnt update the actual object. I have even implemented the
UserControl
from
INotifyPropertyChanged
, and invoked the event when the value is changed on the
TextBox
, but alas, it didnt worked for me. Can anyone help me in this regard.
If you want to see the code you can download from here:
TextCalc.zip (80 KB)