c# - WPF:如何从项目控件中查找数据模板中的元素

标签 c# wpf data-binding datatemplate itemscontrol

我有以下问题:应用程序正在使用名为 ToolBox 的自定义项控件。工具箱的元素称为工具箱项,是自定义内容控件。现在,工具箱存储了许多从数据库中检索并显示的图像。为此,我在工具箱控件中使用了一个数据模板。但是,当我尝试拖放元素时,我没有得到图像对象,而是得到了数据库组件。我认为我应该遍历结构以找到 Image 元素。这是代码:

工具箱:

public class Toolbox : ItemsControl
    {
        private Size defaultItemSize = new Size(65, 65);
        public Size DefaultItemSize
        {
            get { return this.defaultItemSize; }
            set { this.defaultItemSize = value; }
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ToolboxItem();
        }

        protected override bool IsItemItsOwnContainerOverride(object item)
          {
              return (item is ToolboxItem);
          }
    }

工具箱项:

public class ToolboxItem : ContentControl
    {
        private Point? dragStartPoint = null;

        static ToolboxItem()
        {
            FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolboxItem), new FrameworkPropertyMetadata(typeof(ToolboxItem)));
        }

        protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseDown(e);
            this.dragStartPoint = new Point?(e.GetPosition(this));
        }
        public String url { get; private set; }


        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (e.LeftButton != MouseButtonState.Pressed)
            {
                this.dragStartPoint = null;
            }

            if (this.dragStartPoint.HasValue)
            {
                Point position = e.GetPosition(this);
                if ((SystemParameters.MinimumHorizontalDragDistance <=
                    Math.Abs((double)(position.X - this.dragStartPoint.Value.X))) ||
                    (SystemParameters.MinimumVerticalDragDistance <=
                    Math.Abs((double)(position.Y - this.dragStartPoint.Value.Y))))
                {
                    string xamlString = XamlWriter.Save(this.Content);



                    MessageBoxResult result = MessageBox.Show(xamlString);
                    DataObject dataObject = new DataObject("DESIGNER_ITEM", xamlString);

                    if (dataObject != null)
                    {
                        DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy);
                    }
                }

                e.Handled = true;
            }
        }
        private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                    return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }

    }

这是工具箱和工具箱项的 xaml 文件:

    <Style TargetType="{x:Type s:ToolboxItem}">
        <Setter Property="Control.Padding"
                Value="5" />
        <Setter Property="ContentControl.HorizontalContentAlignment"
                Value="Stretch" />
        <Setter Property="ContentControl.VerticalContentAlignment"
                Value="Stretch" />
        <Setter Property="ToolTip"
                Value="{Binding ToolTip}" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type s:ToolboxItem}">
                    <Grid>
                        <Rectangle Name="Border"
                                   StrokeThickness="1"
                                   StrokeDashArray="2"
                                   Fill="Transparent"
                                   SnapsToDevicePixels="true" />
                        <ContentPresenter Content="{TemplateBinding ContentControl.Content}"
                                          Margin="{TemplateBinding Padding}"
                                          SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" 
                                          ContentTemplate="{TemplateBinding ContentTemplate}"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver"
                                 Value="true">
                            <Setter TargetName="Border"
                                    Property="Stroke"
                                    Value="Gray" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style TargetType="{x:Type s:Toolbox}">
        <Setter Property="SnapsToDevicePixels"
                Value="true" />
        <Setter Property="Focusable"
                Value="False" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                     <Border BorderThickness="{TemplateBinding Border.BorderThickness}"
                            Padding="{TemplateBinding Control.Padding}"
                            BorderBrush="{TemplateBinding Border.BorderBrush}"
                            Background="{TemplateBinding Panel.Background}"
                            SnapsToDevicePixels="True">
                        <ScrollViewer VerticalScrollBarVisibility="Auto">

                            <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />

                            </ScrollViewer>

                    </Border>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <WrapPanel Margin="0,5,0,5"
                               ItemHeight="{Binding Path=DefaultItemSize.Height, RelativeSource={RelativeSource AncestorType=s:Toolbox}}"
                               ItemWidth="{Binding Path=DefaultItemSize.Width, RelativeSource={RelativeSource AncestorType=s:Toolbox}}" />
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

示例用法:

<Toolbox x:Name="NewLibrary" DefaultItemSize="55,55" ItemsSource="{Binding}" >
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel>
                                        <Image Source="{Binding Path=url}" />
                                    </StackPanel>
                                </DataTemplate>

                        </ItemsControl.ItemTemplate>
                            </Toolbox>

我得到的对象是一个数据库对象。使用静态资源时,我得到 Image 对象。如何从数据模板中检索此 Image 对象?我虽然可以使用本教程: http://msdn.microsoft.com/en-us/library/bb613579.aspx 但它似乎并没有解决问题。 谁能提出解决方案? 谢谢!

最佳答案

在 ToolboxItem 的代码后面调用他的方法:

FindVisualChild<Image>(this);

这对我来说工作正常并返回我预期的图像对象。

关于c# - WPF:如何从项目控件中查找数据模板中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2533449/

相关文章:

c# - 尝试反序列化 XML 数组

WPF 绑定(bind)到 Grid.ColumnSpan

c# - 将 DataGrid 绑定(bind)到 ObservableCollection<Dictionary>

Silverlight:设置属性直接删除数据绑定(bind)?

c# - 你如何称呼这种二进制数据类型,以及如何在 C# 中处理它?

c# - 使用 IEnumerable<T> 作为委托(delegate)返回类型

c# - 组装 ... 内部和外部命名空间

c# - 如何将函数分派(dispatch)给gui线程?

wpf 字符串格式整数 1234 到 12 :34 only in XAML

android - 使用数据绑定(bind)后查看边距不起作用