我实际上是在尝试以异步方式添加一些 UIElement在我的 MainPage 中定义我的 Canvas 。
据我了解,将 UIElement
添加到 Canvas
的基本方法是将其添加到他的 UIElementCollection 上,例如我应该这样做的一条线:
Line line = new Line();
// Line attributes
line.Stroke = new SolidColorBrush(Colors.Purple);
line.StrokeThickness = 15;
Point point1 = new Point();
point1.X = 0;
point1.Y = 0;
Point point2 = new Point();
point2.X = 480;
point2.Y = 720;
line.X1 = point1.X;
line.Y1 = point1.Y;
line.X2 = point2.X;
line.Y2 = point2.Y;
// Line attributes
MyCanvas.Children.Add(line);
假设我有一个名为 Graphics 的类,它需要访问此 Canvas 才能在其上绘图。
public class Graphics
{
public void drawLine()
{
//Using Dispatcher in order to access the main UI thread
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Line line = new Line();
// Line attributes
/**
* Here I want to access the Canvas of the MainPage
* I have no Idea what to put here !!!
*
**/
});
}
}
在“我不知道该放什么!!!”的地方我试图直接访问 MainPage Canvas --> 失败
我试图在 MainPage 中声明一个 public static UIElementCollection 以便添加我的 UIElement 然后将它传递给 Canvas 但不可能,因为 UIElementCollection 没有构造函数 --> 失败
但这些想法似乎是肮脏的编码,并不真正优雅。因此,通过我的研究,我发现 MVVM 应该可以发挥神奇作用。但是我找到的所有教程都是通过 xaml 文件进行数据绑定(bind)的,这在我的案例中是无法使用的。
所以我有两个问题:
第一:如何使用Canvas的UIElementCollection? (有没有像JAVA中的Paint或者Repaint一样隐藏的叫who draw it的方法?)
第二:如果我想遵循 MVVM 模式,我可以将 MainPage 视为我的 View ,将 Graphics 类视为我的 ViewModel 和 UIElement 作为我的模特?
最佳答案
这是一个非常基本的示例,但应该让您朝着正确的方向前进。
图形.cs
public class Graphics
{
public ObservableCollection<UIElement> UIElements { get; set; }
int poisiton = 0;
private Timer backgroundTimer;
public Graphics()
{
this.UIElements = new ObservableCollection<UIElement>();
this.backgroundTimer = new Timer(new TimerCallback((timer) => {
Deployment.Current.Dispatcher.BeginInvoke(() => this.GenerateLine());
}), null, 2000, 3000);
}
private void GenerateLine()
{
Line line = new Line();
// Line attributes
line.Stroke = new SolidColorBrush(Colors.Purple);
line.StrokeThickness = 15;
Point point1 = new Point();
point1.X = this.poisiton;
point1.Y = this.poisiton;
Point point2 = new Point();
point2.X = this.poisiton;
point2.Y = this.poisiton + 30;
line.X1 = point1.X;
line.Y1 = point1.Y;
line.X2 = point2.X;
line.Y2 = point2.Y;
// Line attributes
this.poisiton += 10;
UIElements.Add(line);
}
}
MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
this.Loaded += MainPage_Loaded;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var graphics = new Graphics();
this.ContentPanel.DataContext = graphics;
}
主页.xaml
<Canvas x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ItemsControl ItemsSource="{Binding UIElements}">
</ItemsControl>
</Canvas>
希望对您有所帮助。
关于c# - 以异步方式以编程方式将 UIElement 添加到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17667757/