我从 WP7 开始,尝试更改 TexBlock 的颜色和其他属性。它包含在列表框中并绑定到集合。我正在寻找像“OnDataBound”这样的方法。该值必须根据绑定对象而变化。
<ListBox HorizontalAlignment="Left" Name="listBox1" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="{StaticResource PhoneForegroundBrush}" Width="418" BorderThickness="1" Margin="2">
<StackPanel Orientation="Vertical" >
<StackPanel Orientation="Horizontal"><TextBlock Text="Charater: "/><TextBlock Text="{Binding Path=CharacterName}" TextWrapping="Wrap" /></StackPanel>
<StackPanel Orientation="Horizontal"><TextBlock Text="Perk launched: "/><TextBlock Text="{Binding Path=CreationDate}" TextWrapping="Wrap"/></StackPanel>
<StackPanel Orientation="Horizontal"><TextBlock Text="Finished at: "/><TextBlock Text="{Binding Path=FinishedAt}" TextWrapping="Wrap"/></StackPanel>
<StackPanel Orientation="Horizontal"><TextBlock x:Name="TextBlockStatus" Text="Status: "/><TextBlock Text="{Binding Path=Status}" TextWrapping="Wrap"/></StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
取决于绑定对象的状态,我需要更改 Textblock 的属性(颜色等) 你能告诉我要点吗?
我的绑定如下(在.cs中):
this.listBox1.DataContext = this.calculatedValues;
感谢您的帮助
在此示例中,颜色存储在名为 ListItems 的类中,定义为:
public class ListItems
{
public string name { get; set; }
public string color { get; set; }
}
ListItems 类型的可观察集合被添加到 MainPage 文件后面的代码中:
public partial class MainPage : PhoneApplicationPage
{
ObservableCollection<ListItems> items = new ObservableCollection<ListItems>();
// Constructor
public MainPage()
{
InitializeComponent();
items.Add(new ListItems() { name = "Item 1", color = "Red" });
items.Add(new ListItems() { name = "Item 2", color = "Blue" });
items.Add(new ListItems() { name = "Item 3", color = "Green" });
items.Add(new ListItems() { name = "Item 4", color = "White" });
items.Add(new ListItems() { name = "Item 5", color = "Purple" });
DataContext = this;
listBox1.ItemsSource = items;
}
}
}
ListItem 类型的项目将添加到可观察集合中。
然后,MainPage.xaml 文件被设计为包含一个列表框,该列表框的 ItemTemplate 绑定到 ListItem 类的属性:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox HorizontalAlignment="Left" Margin="12" Width="400" Height="400" Name="listBox1" VerticalAlignment="Top" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="Item" Text="{Binding name}" FontFamily="Arial" FontSize="40" Foreground="{Binding color}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
完成的页面如下所示:
希望这有帮助。