如何将带有绘图的画布放在ListView控件的某些列中?

时间:2013-07-21 08:06:11

标签: c# wpf xaml

如何将带有绘图的画布放在ListView控件的某些列中?

我有这个:

<DataTemplate>
    <Canvas Width="60" Height="20" Background="Red" ClipToBounds="True" >
        <ContentPresenter Content="{Binding Path=Graph}" />
    </Canvas>
</DataTemplate>

var canvas = new Canvas();
canvas.Children.Add(new Ellipse(){});
var items = new ObservableCollection<LvItem>() { new LvItem(){ Graph = canvas} };
myListView.ItemsSource = items;

但是它显示System.Windows.Controls.Canvas作为文本,而不是画布本身及其图纸。

1 个答案:

答案 0 :(得分:2)

它正在运行,请查看以下示例。

XAML:

<ListView Name="myListView" >
    <ListView.View>
        <GridView>
            <GridViewColumn Width="140" Header="Grap">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Canvas Width="60" Height="50" Background="Red" ClipToBounds="True" >
                            <ContentPresenter Content="{Binding Path=Graph}" />
                        </Canvas>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>                    
        </GridView>
    </ListView.View>
</ListView>

LvItem类:

class LvItem
{
    public Canvas Graph { get; set; }
}

代码隐藏:

var canvas = new Canvas();
canvas.Children.Add(new Ellipse() { Width = 50, Height = 50, Fill = new SolidColorBrush(Colors.Yellow) });
var canvas2 = new Canvas();
canvas2.Children.Add(new Ellipse() { Width = 50, Height = 50, Fill = new SolidColorBrush(Colors.Blue) });
var items = new ObservableCollection<LvItem>() { new LvItem() { Graph = canvas }, new LvItem() { Graph = canvas2 } };
myListView.ItemsSource = items;

结果:

enter image description here