使用一种样式,将多个对象绑定到一个列表
本文关键字:对象 绑定 一个 列表 一种 样式 | 更新日期: 2023-09-27 18:20:03
我有N个DataPoints和一个N长度的字符串列表。我想创建一个样式资源,可以应用于将每个TextBlock绑定到列表中某个元素的每个DataPoint。像这样的
<Style TargetType="charting:DataPoint" x:Key="annotatedChart">
<Setter Property="Background" Value="CornflowerBlue"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="charting:DataPoint">
<Grid>
<Rectangle
Fill="{TemplateBinding Background}"
Stroke="Black"/>
<Grid
Background="#aaffffff"
Margin="0 -20 0 0"
HorizontalAlignment="Center"
VerticalAlignment="Top">
<TextBlock
x:Name="textBox"
Text="{Binding}" <!--TODO -->
FontWeight="Bold"
Margin="2"/>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我需要将该文本绑定到一个列表,以便具有此样式的每个数据点都将显示列表中的匹配文本元素。我曾尝试将主窗口的DataContext设置为几个对象和属性,但都无济于事。有一段时间,我的DataPoints显示Dependent和Independent值,但从未显示字符串列表中的任何值。
我想明白了。我制作了一个独立值和标签的字典,将其设置为我的窗口的DataContext,并使用IValueConverter将文本框绑定到它,该转换器在字典中找到依赖值并将其映射到标签。
<TextBlock
x:Name="textBox"
Text="{Binding Key, Converter={StaticResource annotationsConverter}}"
FontWeight="Bold"
Margin="2"
TextWrapping="Wrap"/>
和
public class myAnnotationsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (MainWindow.annotations != null)
{
try
{
return MainWindow.annotations[value as string];
}
catch (KeyNotFoundException e)
{
return "NULL";
}
}
throw new NotFiniteNumberException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotFiniteNumberException();
}
}
可能的改进:在类别轴中,每个类别支持多个列。因此,如果我在2007年6月有三个酒吧,请为所有酒吧保留一个独特的标签。