views:

36

answers:

1

Main WINDOW

<Window x:Class="dep2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:dep2"
    Title="Window1" Height="300" Width="381">
    <Grid>
        <local:UserControl1></local:UserControl1>
        <Button Height="23" HorizontalAlignment="Right" Margin="0,0,77,36" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Button</Button>
    </Grid>
</Window>

public partial class Window1 : Window
{
    UserControl1 uc = new UserControl1();
    public Window1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        uc.InfoText = "SAMPLE";
    }
}

My User CONTROL

<UserControl x:Class="dep2.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="32" Width="300">
    <Grid Height="30">
        <StackPanel Background="LightCyan">
            <TextBox Height="21" Name="textBlock1" Width="120"  Text="{Binding Text}" />
        </StackPanel>


    </Grid>
</UserControl>



public partial class UserControl1 : UserControl
{
    public string InfoText
    {
        get
        {
            return (string)GetValue(InfoTextProperty);
        }
        set
        {
            SetValue(InfoTextProperty, value);
        }
    }

    public static readonly DependencyProperty InfoTextProperty =
       DependencyProperty.Register(
          "InfoText",
          typeof(string),
          typeof(UserControl1),
          new FrameworkPropertyMetadata(
             new PropertyChangedCallback(ChangeText)));

    private static void ChangeText(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        (source as UserControl1).UpdateText(e.NewValue.ToString());
    }

    private void UpdateText(string NewText)
    {

        textBox1.Text = NewText;

    } 


    public UserControl1()
    { 
        InitializeComponent();
        DataContext = this;


    } 
} 

Am getting my value in user control dependency property, but i cant able to bind my value to the text box.am using like this to bind Text="{Binding Text}" is it right,or how to bind my value in user control

i have attached my sample project here, http://cid-08ec3041618e8ee4.skydrive.live.com/self.aspx/.SharedFavorites/dep2.rar

Can any one look and tell whats wrong in that,

everythng working well, but i cant bind the value in text box,

when u click the button u can see the passed value to usercontrol in message box, but i cant bind that value in text box.

Why????

+2  A: 

Your code handles the callback from the dependency property and sets the text box value directly. This is not the role of this callback.

And by setting the Text property, you have lost the binding. Local property setting has a higher priority than bindings. See this blog

Timores