如何将带有图纸的画布放在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显示为文本,而不是画布本身及其图形。

最佳答案

工作正常,请查看下面的示例。

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;


结果:

09-10 04:18