(C#)以编程方式进行数据绑定布局

本文关键字:数据绑定 布局 方式进 编程 | 更新日期: 2023-09-27 18:37:04

我有这个带有帐户网格的 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 (Account.Account account in GetModel().BalancePageModel.Accounts)
{
    var myAccountInfoControl = new AccountInfo(account);
    //myAccountInfoControl.txtLabel.SetBinding()
    AccountsInfo.Children.Add(myAccountInfoControl);
}

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

(C#)以编程方式进行数据绑定布局

您必须将

myAccountInfoControl 的 DataContext 设置为帐户对象。 myAccountInfoControl.DataContext = account;

如果执行此操作,则应通过删除"帐户"部分来更改在 XAML 中完成的绑定,如下所示:

希望这有帮助。