2

我正在用 c# 开发一个 Metro 应用程序(Windows 8),它允许;拖动控件/元素(按钮、文本框等),我不确定如何在 Metro 应用程序中进行拖动。请指导我,在此先感谢

4

1 回答 1

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);
    }
}
于 2013-03-26T09:20:06.497 回答