我有个控件,放在Canvas中,然后添加到窗体的grid中
grid.Children.add(canvas);要如何控制它的显示位置比如我鼠标在任意位置MouseDown
然后控件就现实在我鼠标点下的位置.

解决方案 »

  1.   

    假设控件为一个TextBox        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
            {
                Point p = e.GetPosition(grid1);
                textBox1.SetValue(Grid.MarginProperty, new Thickness(p.X, p.Y, 0, 0));
                base.OnMouseLeftButtonDown(e);
            }同理也可以设置相对canvas的位置。
      

  2.   

    override?它继承的哪个类?我是在mousedown事件里写的你的重写方法,怎么调用?
      

  3.   

        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
                this.MouseDown += new MouseButtonEventHandler(Window1_MouseDown);
            }        void Window1_MouseDown(object sender, MouseButtonEventArgs e)
            {
                Button btn = new Button();
                btn.Content = "test";
                btn.Width = 100;
                btn.Height = 100;
                grid.Children.Add(btn);            Point p = e.GetPosition(grid);
                btn.SetValue(Grid.MarginProperty, new Thickness(p.X, p.Y, 0, 0));
                base.MouseDown(e);
            }
        }
    }结果在最后一句出错事件“System.Windows.UIElement.MouseDown” 只能出现在+=或-=左边
      

  4.   

    用margin给控件绝对定位?
    位置不对的。我以前就是这样弄的这样写的话,我宽屏幕。控件是在鼠标右下角,还挺远的
      

  5.   

    也可以设置Grid.RowProperty,Grid.ColumnProperty等等,你是程序员,不是美工,要举一反三,否则.net类库这么庞大,何时才能到头?