WPF C#ListBoxItem代码隐藏为If语句

时间:2011-04-21 20:13:01

标签: c# wpf string listboxitems

这看似简单,但我无法弄清楚!在这里寻求一点帮助。我有一堆ListBoxItems,并希望它们在删除时转储不同的文本。

是否可以根据drop事件的ListBoxItem名称生成if语句?

XAML:

<ListBoxItem x:Name="ActionItem">
<Image Source="Action.png" Height="60" Width="60" ToolTip="Action"/>

    

代码背后:

private void DropImage(object sender, System.Windows.DragEventArgs e)
    {
                    {

            ImageSource image = e.Data.GetData(typeof(ImageSource)) as ImageSource;

            Image imageControl = new Image() { Width = image.Width, Height = image.Height, Source = image };

            Canvas.SetLeft(imageControl, e.GetPosition(this.MyCanvas).X);

            Canvas.SetTop(imageControl, e.GetPosition(this.MyCanvas).Y);

            this.Canvas.Children.Add(imageControl);

            TextBox.Text = ("This is a test!");
        }

我应该将listboxitems转换为字符串,然后为每个字符串执行if语句吗?感谢

3 个答案:

答案 0 :(得分:0)

您应该能够围绕DropImage方法放置IF或Case语句。

我要做的是创建一个继承ListBoxItem的新ListBoxItem控件,并添加一个名为“Drop Text”的Dependecy属性。

然后,当您添加List Items时,设置Drop Text String Dependency Property,当您将项目放到Canvas上时,只需将TextBox.Text更改为ListBoxItem上的Property即可。

希望我能按照你的想法走上正轨。

答案 1 :(得分:0)

希望这个链接可以帮助你.....

Drag and Select ListBox Items?

答案 2 :(得分:0)

我不确定我是否正确解决了这个问题...但也许它会有所帮助。

<StackPanel>
        <ListBox AllowDrop="True">
            <ListBoxItem x:Name="ActionItem" PreviewMouseDown="ActionItem_PreviewMouseDown">
                <Image Source="links.png" Height="60" Width="60" ToolTip="Action" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=Name}"/>
            </ListBoxItem>
        </ListBox>

        <Canvas Height="100" AllowDrop="True" Name="MyCanvas" Drop="Canvas_Drop" Background="Azure"/>
        <TextBox Name="MyTextBox">Text</TextBox>
    </StackPanel>

和代码:

private void Canvas_Drop(object sender, DragEventArgs e)
    {
        Image image = e.Data.GetData(typeof(Image)) as Image;
        ListBoxItem lbi = image.Parent as ListBoxItem;
        Image imageControl = new Image() { Width = image.Width, Height = image.Height, Source = image.Source };

        Canvas.SetLeft(imageControl, e.GetPosition(this.MyCanvas).X);
        Canvas.SetTop(imageControl, e.GetPosition(this.MyCanvas).Y);
        this.MyCanvas.Children.Add(imageControl);

        MyTextBox.Text = string.Format("ListBoxItem name is: through item {0}, through image tag: {1}", lbi.Name, image.Tag);
    }

    private void ActionItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        ListBoxItem lbi = (ListBoxItem)sender;
        DragDrop.DoDragDrop(lbi, lbi.Content, DragDropEffects.Copy);
    }