我正在用c#开发一个metro应用程序(Windows 8),允许;拖动控件/元素(按钮,文本框等),我不知道如何拖动地铁应用程序。 请指导我, 在此先感谢
答案 0 :(得分: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);
}
}