目前,我已从此示例的列表框中创建了一个条形图: http://weblogs.thinktecture.com/cnagel/2011/06/wpf-listbox-as-bar-chart.html
我想要做的是改变条形的颜色。我的图表有5个条形,每个条形图都有不同的颜色。基本上我想改变矩形的填充。
修改 ItemsControl似乎不再获取任何内容,我的图表也不可见。
public class GrafiekBar : INotifyPropertyChanged
{
private int value;
private Brush fill = Brushes.Blue;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public List<GrafiekBar> GetDataGrafiek()
{
int[] getallen = new int[] { 3, 5, 8, 6, 2 };
List<GrafiekBar> list = new List<GrafiekBar>();
for (int i = 0; i < getallen.Length; i++)
{
GrafiekBar bar = new GrafiekBar();
bar.Value = getallen[i];
bar.Fill = Brushes.Blue;
list.Add(bar);
}
return list;
}
/// <summary>
/// Implement INotifyPropertyChanged in properties
/// http://msdn.microsoft.com/en-us/library/ms229614.aspx
/// </summary>
public int Value
{
get { return this.value; }
set
{
if (value != this.value)
{
this.value = value;
NotifyPropertyChanged("Value");
}
}
}
public Brush Fill
{
get { return this.fill; }
set
{
if (value != this.fill)
{
this.fill = value;
NotifyPropertyChanged("Fill");
}
}
}
}
XAML:
<ObjectDataProvider x:Key="odpLbGrafiek" ObjectType="{x:Type myClasses:GrafiekBar}" MethodName="GetDataGrafiek"/>
<ObjectDataProvider x:Key="odpLbGrafiekColors" ObjectType="{x:Type myClasses:GrafiekBar}" MethodName="Fill"/>
<DataTemplate x:Key="GrafiekItemTemplate">
<Border Width="Auto" Height="Auto">
<Grid>
<Rectangle x:Name="recGrafiek" Fill="{Binding Source={StaticResource odpLbGrafiekColors}}" StrokeThickness="0"
Height="45" Width="{Binding}" Margin="13.2"
HorizontalAlignment="Right" VerticalAlignment="Bottom">
<Rectangle.LayoutTransform>
<ScaleTransform ScaleX="20" />
</Rectangle.LayoutTransform>
</Rectangle>
</Grid>
</Border>
</DataTemplate>
<ItemsControl x:Name="icGrafiek"
Margin="0"
ItemsSource="{Binding Source={StaticResource odpLbGrafiek}}"
ItemTemplate="{DynamicResource GrafiekItemTemplate}"
Grid.RowSpan="5"
Grid.Column="1" Background="{x:Null}" HorizontalAlignment="Left" RenderTransformOrigin="0.5,0.5"
>
<ItemsControl.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="180"/>
<TranslateTransform/>
</TransformGroup>
</ItemsControl.RenderTransform>
</ItemsControl>
最好的问候。
答案 0 :(得分:1)
您应该始终避免与用于模板的控件直接交互,而是bind更改为项目所需的所有内容,然后在项目上编辑相关属性。
除了仅使用值之外,您还需要一组更复杂的对象,至少它们需要两个属性:
public class Bar : INotifyPropertyChanged
{
public double Value { get; set; } // Implement interface in those properties for binding
public Brush Fill { get; set; }
}
<!-- in the template -->
<Rectangle Width="{Binding Value}" Fill="{Binding Fill}" .../>
var bar = (Bar)lbGrafiek.Items.CurrentItem;
bar.Fill = Brushes.Red;