本文介绍了自定义类中的XAML控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了简单的项目WpfApplication1并将CanvasmyCanvas插入到XAML中,我试图在TestClass类中使用myCanvas但是不能,请帮助我......



如何在TestClass中调用myCanvas?

I created simple project "WpfApplication1" and inserted Canvas "myCanvas" into XAML and I tried to use "myCanvas" inside that class "TestClass" but couldn't, Please help me...

how I can call "myCanvas" inside "TestClass"?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WpfApplication1
{
    class TestClass
    {
    }
}




<Window x:Class="WpfApplication1.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Canvas Name="myCanvas" HorizontalAlignment="Left" Height="137" Margin="122,90,0,0" VerticalAlignment="Top" Width="277" Background="Green"/>
    </Grid>
</Window>




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

推荐答案

public TestClass(Mainwindow window)
{
   window.myCanvas.Background = Brushes.Red;
}



并写在MainWindow上


And write on MainWindow

var obj = TestClass(this);



All is Done。


And All is Done.


namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

//here you can set any property value of your canvas. this is sample demonstrate code how to access not complete running example anymore.
    public Control myCanvas { get; set;}
}


var canvas = ((MainWindow)Application.Current.MainWindow).Get_Canvas;





但我不认为从其他类型访问控件是个好主意。你应该重新考虑为什么你需要从另一种类型引用'myCanvas'。在xaml中实例化的对象是私有的有一个原因。


希望有所帮助。

Uros



However I don't think that accesing controls from another type is a good idea. You should reconsider why you need a reference to 'myCanvas' from another type. There is a reason why objects instantiated in xaml are private.

Hope that helps.
Uros


这篇关于自定义类中的XAML控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 13:52