我用C#代码创建Textblocks,我想将JSON数据绑定到它。此刻我想这样做:
if (actualStock == true)
{
TextBlock TBActualStock = new TextBlock();
TBActualStock.Text = "Actuele voorraad: ";
TBActualStock.FontSize = 18;
STACKActualStockDeliverTime.Children.Insert(1, TBActualStock);
TextBlock TBBindActualStock = new TextBlock();
TBBindActualStock.Text = "{Binding ActualStock}"; //this is where it should bind
TBBindActualStock.FontSize = 18;
STACKActualStockDeliverTime2.Children.Insert(1, TBBindActualStock);
}
这是我的XAML代码:
DataContext="{Binding Item}"
d:DataContext="{Binding Groups[0].Items[0]}">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.Background>
<ImageBrush ImageSource="/Assets/BackGroundGAC.jpg" Stretch="UniformToFill"/>
</Grid.Background>
<Grid Grid.Row="1" x:Name="contentRegion">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<StackPanel x:Name="STACKActualStockDeliverTime">
<TextBlock x:Name="HEADERActualStockDeliverTime" FontSize="24" Text="Voorraad en levertijd"></TextBlock>
</StackPanel>
<StackPanel x:Name="STACKActualStockDeliverTime2">
<TextBlock x:Name="Headert" FontSize="24" Text=""></TextBlock>
</StackPanel>
</StackPanel>
现在我想将Json数据添加到我在C#代码中创建的文本块中。我知道在XAML中我应该使用{Binding description} //description is a part of my json object so that works
但是如果我在C#代码中这样做,它只会将文本设置为{Binding Description}
知道如何解决这个问题吗?
ps:我需要用C#代码而不是XAML代码。
答案 0 :(得分:0)
如果您在代码中绑定,则不应该这样做,只需指定值
即可 TextBlock TBBindActualStock = new TextBlock();
TBBindActualStock.Text = ActualStock ;
如果要在代码中绑定,请使用“绑定操作”,
Binding binding = new Binding();
binding.Path = new PropertyPath("ActualStock");
binding.Source = sourceObject;
BindingOperations.SetBinding(TBBindActualStock, TextBlock.TextProperty, binding);
来自Binding String Property in Code-Behind TextBlock
在XAML中,
<TextBlock Text="{Binding ActualStock}
答案 1 :(得分:0)
你可以像这样使用Binding类
Binding myBinding = new Binding("ActualStock");
myBinding.Source = myDataObject;//here is your data source.
TBBindActualStock.SetBinding(TextBlock.TextProperty, myBinding);