2012-11-06 73 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); 
    } 
} 
相關問題