(C#)DataBinding布局以编程方式

时间:2016-03-02 11:18:08

标签: c# asp.net xaml windows-phone-7 data-binding

我有这个xaml与帐户网格:

<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>

我正在以编程方式为每个使用foreach的帐户添加此布局:

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

我的布局已创建,但AvailableStr,txtLabel和ReservedStr的值没有变化,因为我还没有以编程方式启用数据绑定,我该怎么做?

1 个答案:

答案 0 :(得分:0)

您必须将myAccountInfoControl的DataContext设置为帐户对象。 myAccountInfoControl.DataContext = account;

如果您这样做,您应该通过删除&#34;帐户更改您在XAML中所做的绑定。&#34;像这样的部分:

希望得到这个帮助。