WPF在ListView中绘制带有文本的圆圈

时间:2017-01-26 13:43:42

标签: c# wpf canvas

我试图在Canvas上做,但结果很糟糕。 Text和PathGeometry具有不同的中心。怎么解决?用文字绘制圆圈的最佳方法是什么?

的Xaml:

<Grid>
        <ListView ItemsSource="{Binding Items}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Path Stroke="Black" StrokeThickness="1" Fill="Aqua" VerticalAlignment="Center" HorizontalAlignment="Center">
                            <Path.Data>
                                <EllipseGeometry Center="{Binding Path=Point}" RadiusX="{Binding Radius}" RadiusY="{Binding Radius}" />
                            </Path.Data>
                        </Path>
                        <TextBox Text="Test" VerticalAlignment="Center" HorizontalAlignment="Center" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></TextBox>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas Height="500" Width="500"></Canvas>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>
    </Grid>

代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}
public class ViewModel
{
    public ObservableCollection<Circle> Items { get; set; }
    public ViewModel()
    {
        Items = new ObservableCollection<Circle>();
        Random random = new Random();
        for (int i = 0; i < 10; i++)
        {
            Circle circle = new Circle();
            circle.Radius = random.Next(1, 40);
            circle.Point = new Point(random.Next(1, 500), random.Next(1, 500));

            Items.Add(circle);
        }
    }

}
public class Circle
{
    public int Radius { get; set; }
    public Point Point { get; set; }
}

1 个答案:

答案 0 :(得分:0)

将此作为DataTemplate

<Border
    Width="{Binding Radius}"
    Height="{Binding Radius}"
    CornerRadius="{Binding Radius}"
    Background="Aqua"
    BorderBrush="Black"
    BorderThickness="1">
    <TextBlock
        VerticalAlignment="Center"
        HorizontalAlignment="Center"
        Text="Test"/>
</Border>

您可以在Centering Text on a WPF Shape

找到更多解决方案

修改 您还需要在边框中设置Canvas.Left,...以将其放置在您想要的位置