有一个显示圆圈的代码(使用宽度和高度相等的 ellipse
,还使用 reactive ui
进行通知)我想在 Canvas 中间画一个圆圈,但还要管理调整大小更新。
当前代码集Canvas Left
和 Canvas Top
,但我不确定如何在中间设置圆圈并填充几乎所有 Canvas 。
类:
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);
}
}
xml:
<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>
这会产生:
我该如何更改 xml 或 后面的代码将圆圈居中并将其设置为几乎与 Canvas 一样的大小?:
最佳答案
通过将椭圆大小绑定(bind)到 Canvas 大小并使用将输入值转换为(例如) Canvas 大小的 0.9 倍的转换器,使您的椭圆几乎与 Canvas 一样大,如下所示:
XAML
<Canvas Name="MyCanvas">
<Ellipse Height="{Binding ElementName=MyCanvas, Path=ActualHeight, Converter={StaticResource MyScaleConverter}}" Width="{Binding ElementName=MyCanvas, Path=ActualWidth, Converter={StaticResource MyScaleConverter}}"></Ellipse>
</Canvas>
C#
public class ScaleZeroNine : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToDouble(value) * 0.9;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
关于中心问题:
你为什么还要使用 Canvas ?有什么具体原因吗? Canvas 使使用 WPFs 的全部功能变得困难,因为它的安排更像是 winForms。例如,当使用网格时,它将自动居中,也可以定义为这样做
关于c# - 如何使用 MVVM 根据 Canvas 大小居中形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54139973/