【发布时间】:2019-01-11 03:26:30
【问题描述】:
有一个显示圆圈的代码(使用宽度和高度相等的ellipse,还使用reactive ui 通知)我想在画布中间画一个圆圈,但也管理调整大小更新。
当前代码设置Canvas Left和Canvas Top,但我不知道如何在中间设置圆圈并填充几乎所有画布。
类:
public class MyViewModel : ReactiveObject
{
public ObservableCollection<IShape> Shapes
{
get => _shapes;
set => this.RaiseAndSetIfChanged(ref _shapes, value);
}
private ObservableCollection<IShape> _shapes;
public MainViewModel()
{
//here the location is set, but how to adjust it to the center of canvas?
Shapes = new ObservableCollection<IShape>
{
new Circle {
Top = 100,
Left = 100,
Radius = 50,
Color = Color.FromArgb(255, 233,222, 0)
}
};
}
}
public interface IShape
{
int Top { get; set; }
int Left { get; set; }
}
public abstract class Shape : ReactiveObject, IShape
{
private int _top;
private int _left;
public int Top
{
get { return _top; }
set { this.RaiseAndSetIfChanged(ref _top, value); }
}
public int Left
{
get { return _left; }
set { this.RaiseAndSetIfChanged(ref _left, value); }
}
}
public class Circle : Shape
{
private int _radius;
private Color _color;
public int Radius
{
get => _radius;
set => this.RaiseAndSetIfChanged(ref _radius, value);
}
public System.Windows.Media.Color Color
{
get => _color;
set => this.RaiseAndSetIfChanged(ref _color, value);
}
}
xaml:
<ItemsControl ItemsSource="{Binding Path=Shapes}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type entities:Circle}">
<Ellipse Width="{Binding Radius}"
Height="{Binding Radius}"
Canvas.Top="{Binding Top, Mode=TwoWay}"
Canvas.Left="{Binding Left, Mode=TwoWay}"
>
<Ellipse.Stroke>
<SolidColorBrush Color="{Binding Color}" />
</Ellipse.Stroke>
</Ellipse>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Top" Value="{Binding Path=Top, Mode=TwoWay}" />
<Setter Property="Canvas.Left" Value="{Binding Path=Left, Mode=TwoWay}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
这会产生:
如何将 xaml 或 code behind 更改为居中并将圆设置为几乎与画布一样的大小?:
【问题讨论】: