Search code examples
c#asp.netxamlwindows-phone-7data-binding

(C#) DataBinding layout programmatically


I have this xaml with grid of accounts:

<UserControl x:Class="SpectroCoin.Controls.AccountInfo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:effects="clr-namespace:SpectroCoin.Effects"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="130" d:DesignWidth="480">
    <UserControl.Resources>
        <Style x:Key="MainInfoStyle" TargetType="TextBlock">
            <Setter Property="FontSize" Value="32"/>
            <Setter Property="VerticalAlignment" Value="Bottom"/>
        </Style>
        <Style x:Key="ReservedInfoStyle" TargetType="TextBlock">
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="VerticalAlignment" Value="Bottom"/>
        </Style>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Margin="0,0,0,0" >
        <StackPanel Orientation="Vertical" Grid.Column="0" Margin="0,0,0,0">
            <TextBlock FontSize="24" Text="Label" x:Name="txtLabel" Margin="0"/>
            <TextBlock FontSize="50" Text="{Binding Account.AvailableStr}" Margin="50,-10,0,0" Foreground="#FFF9AF28"/>
            <TextBlock FontSize="24" Margin="50,-15,0,0" Visibility="{Binding ReservedVisibility}">    
                <Run Foreground="Gainsboro" Text="{Binding LocalizedResources.reserved, Source={StaticResource LocalizedStrings}, StringFormat='\{0\} '}"/>
                <Run Foreground="Gainsboro" Text="{Binding Account.ReservedStr}"/>
            </TextBlock>
        </StackPanel>
    </Grid>
</UserControl>

And I am adding this layout programatically for every account I have using foreach:

foreach (Account.Account account in GetModel().BalancePageModel.Accounts)
{
    var myAccountInfoControl = new AccountInfo(account);
    //myAccountInfoControl.txtLabel.SetBinding()
    AccountsInfo.Children.Add(myAccountInfoControl);
}

My layout is created, but the values of AvailableStr, txtLabel and ReservedStr doesn't change because I haven't enabled Databinding programatically, how do I do that?


Solution

  • You have to set the DataContext of myAccountInfoControl to the account object. myAccountInfoControl.DataContext = account;

    If you do this the bindings that you have done in the XAML should be changed by removing the "Account." part like this:

    Hope this help.