Thursday, March 31, 2011

Why is two-way binding in silverlight not working?

According to how Silverlight TwoWay binding works, when I change the data in the FirstName field, it should change the value in CheckFirstName field.

Why is this not the case?

ANSWER:

Thank you Jeff, that was it, for others: here is the full solution with downloadable code.

XAML:

<StackPanel>
    <Grid x:Name="GridCustomerDetails">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="300"/>
        </Grid.ColumnDefinitions>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="0" Grid.Column="0">First Name:</TextBlock>
        <TextBox Margin="10" Grid.Row="0" Grid.Column="1" Text="{Binding FirstName, Mode=TwoWay}"/>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="1" Grid.Column="0">Last Name:</TextBlock>
        <TextBox Margin="10" Grid.Row="1" Grid.Column="1" Text="{Binding LastName}"/>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="2" Grid.Column="0">Address:</TextBlock>
        <TextBox Margin="10" Grid.Row="2" Grid.Column="1" Text="{Binding Address}"/>

    </Grid>

    <Border Background="Tan" Margin="10">
        <TextBlock x:Name="CheckFirstName"/>
    </Border>

</StackPanel>

Code behind:

public Page()
{
    InitializeComponent();

    Customer customer = new Customer();
    customer.FirstName = "Jim";
    customer.LastName = "Taylor";
    customer.Address = "72384 South Northern Blvd.";

    GridCustomerDetails.DataContext = customer;

    Customer customerOutput = (Customer)GridCustomerDetails.DataContext;
    CheckFirstName.Text = customer.FirstName;

}
From stackoverflow
  • Your Customer type has to support INotifyPropertyChanged in order for the binding to know when your FirstName property value has changed.

    This tutorial may help you in getting your code to work.

    carlmon : You could also derive from `DependencyObject` and make `FirstName` a dependency property. Jeff's solution is more appropriate, but you have the two choices.
    Jeff Yates : @carlmon: Good point, that is an alternative approach to get this working.
  • Just noticed that the link to the tutorial in Jeff's answer is broken. Here's the new one: http://www.silverlight.net/learn/tutorials/databinding-cs/

0 comments:

Post a Comment