2012-11-06 40 views

回答

0

这是完整的源代码。您可以将任何控件拖放到画布上。现在我正在给你按钮和文本框的例子。对于所有其他控制,过程是相同的。

XAML代码

<Grid> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="90"/> 
     <ColumnDefinition /> 
    </Grid.ColumnDefinitions> 
    <GridView 
     x:Name="GridViewControl" 
     AllowDrop="True" 
     Background="#FF2E5073" 
     CanDragItems="True" 
     DragItemsStarting="GridViewControl_DragItemsStarting" 
     SelectionMode="None" 
     > 
     <GridView.ItemTemplate> 
      <DataTemplate> 
       <Grid> 
        <TextBlock 
         FontSize="14" 
         Text="{Binding}" 
         /> 
       </Grid> 
      </DataTemplate> 
     </GridView.ItemTemplate> 
     <GridView.ItemsPanel> 
      <ItemsPanelTemplate> 
       <VirtualizingStackPanel 
        Orientation="Vertical" 
        /> 
      </ItemsPanelTemplate> 
     </GridView.ItemsPanel> 
    </GridView> 
    <Canvas x:Name="Form" 
      AllowDrop="True" 
      Background="Black" 
      Drop="Form_Drop" 
      Grid.Column="1" 
      /> 
</Grid> 

C#代码

public sealed partial class MainPage : Page 
{ 
    public MainPage() 
    { 
     this.InitializeComponent(); 
    } 

    protected override void OnNavigatedTo(NavigationEventArgs e) 
    { 
     var ObserControl = new ObservableCollection<string>() { "Textbox", "Button" }; 
     GridViewControl.ItemsSource = ObserControl; 
    } 

    private void Form_Drop(object sender, DragEventArgs e) 
    { 
     object sourceItem; 
     e.Data.Properties.TryGetValue("Item", out sourceItem); 
     double XPos = e.GetPosition(GridViewControl).X - 160; 
     double YPos = e.GetPosition(GridViewControl).Y; 
     if (sourceItem.ToString() == "Textbox") 
     { 
      var newTextbox = new TextBox(); 
      newTextbox.Text = "Textbox"; 
      newTextbox.SetValue(Canvas.LeftProperty, XPos); 
      newTextbox.SetValue(Canvas.TopProperty, YPos); 
      Form.Children.Add(newTextbox); 
     } 
     if (sourceItem.ToString() == "Button") 
     { 
      var newButton = new Button(); 
      newButton.Content = "Button"; 
      newButton.SetValue(Canvas.LeftProperty, XPos); 
      newButton.SetValue(Canvas.TopProperty, YPos); 
      Form.Children.Add(newButton); 
     } 
    } 

    private void GridViewControl_DragItemsStarting(object sender, DragItemsStartingEventArgs e) 
    { 
     var item = e.Items.FirstOrDefault(); 
     e.Data.Properties.Add("Item", item); 
    } 
} 
相关问题