簡體   English   中英

在列表框中顯示畫布子級

[英]Showing canvas children in listbox

我是新來的,所以如果我錯過添加回答我的問題所需的內容的話,請原諒。

所以這是我的問題:我試圖在畫布上添加形狀,同時還希望在列表框中顯示它們的列表,以使其可更改(大小,位置等)。 我正在使用WPF。 有辦法嗎?

並且,如果它不打擾您,那么是否存在問題或網站,或者關於如何通過鼠標事件動態繪制形狀(圓形,橢圓形,矩形等)的問題?

我希望你能幫助我。 提前致謝。

編輯:鑒於事實,我有:

    public partial class MainWindow : Window
{
    public ObservableCollection<string> Baselist = new ObservableCollection<string>();
    public ObservableCollection<string> Crystallist = new ObservableCollection<string>();
    public ObservableCollection<Shape> Shapelist = new ObservableCollection<Shape>();
    public MainWindow()
    {
        this.ResizeMode = System.Windows.ResizeMode.CanMinimize;
        InitializeComponent();
        InitializeLists(Baseforms,CrystalGroups);
    }

private void InitializeLists(ComboBox Baseforms, ComboBox CrystalGroups)
    {
        Baseforms.ItemsSource = Baselist;
        CrystalGroups.ItemsSource = Crystallist;
        Shape Circle = new Ellipse();
        Circle.Stroke = System.Windows.Media.Brushes.Black;
        Circle.Fill = System.Windows.Media.Brushes.DarkBlue;
        Circle.HorizontalAlignment = HorizontalAlignment.Left;
        Circle.VerticalAlignment = VerticalAlignment.Center;
        Circle.Width = 50;
        Circle.Height = 50;
        Shapelist.Add(Circle);
    }

如何使用ItemsControl在畫布的Shapelist中顯示形狀,同時在列表框中列出形狀?

希望這可以使問題不再那么廣泛。

請嘗試下一個解決方案:

更新版本(xaml和背后的代碼)

  1. DetailsList列表視圖-顯示基於ShapeDataPresentation類的詳細數據(支持多選)。 通過名為ShapeDataPresentationDataTemplate的數據模板顯示數據。
  2. ShapesPresentor項目控件-在畫布上顯示形狀(不支持多選,只能選擇一個)。

ListView XAML代碼(“ This ”是ListView包含窗口的名稱)

<Window x:Class="ListViewWithCanvasPanel.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:listViewWithCanvasPanel="clr-namespace:ListViewWithCanvasPanel"
    Title="MainWindow" Height="350" Width="525" x:Name="This" ResizeMode="CanResize">
<Grid>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2.5*"></ColumnDefinition>
            <ColumnDefinition Width="4*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <ListView x:Name="DetailsList" Panel.ZIndex="999" Grid.Column="0" ItemsSource="{Binding ElementName=This, Path=Shapes}" SelectionMode="Extended" SelectionChanged="Selector_OnSelectionChanged">
            <ListView.Resources>
                <DataTemplate x:Key="ShapeDataPresentationDataTemplate" DataType="listViewWithCanvasPanel:ShapeDataPresentation">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition></ColumnDefinition>
                            <ColumnDefinition></ColumnDefinition>
                            <ColumnDefinition></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Text="{Binding Name, StringFormat={}{0:N0}%}"></TextBlock>
                        <TextBlock Grid.Column="1">
                            <Run Text="W:"></Run>
                            <Run Text="{Binding OriginalRectAroundShape.Width}"></Run>
                        </TextBlock>
                        <TextBlock Grid.Column="2">
                            <Run Text="H:"></Run>
                            <Run Text="{Binding OriginalRectAroundShape.Height}"></Run>
                        </TextBlock>
                    </Grid>
                </DataTemplate>
            </ListView.Resources>
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate DataType="Shape">
                               <ContentControl Content="{Binding Tag}" ContentTemplate="{StaticResource ShapeDataPresentationDataTemplate}"></ContentControl>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>
        <GridSplitter Grid.Column="0" Width="3" Background="Blue" Panel.ZIndex="999"
          VerticalAlignment="Stretch" HorizontalAlignment="Right" Margin="0"/>
        <ItemsControl Grid.Column="1" x:Name="ShapesPresentor" ItemsSource="{Binding ElementName=This, Path=Shapes}"
                  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                  MouseDown="UIElement_OnMouseDown">
            <!--<ListView.Resources>
                <ControlTemplate x:Key="SelectedTemplate" TargetType="ListViewItem">
                    <ContentControl Content="{Binding }"></ContentControl>
                </ControlTemplate>
            </ListView.Resources>-->
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas Background="White" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <!--<ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Style.Triggers>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsSelected" Value="true" />
                                <Condition Property="Selector.IsSelectionActive" Value="true" />
                            </MultiTrigger.Conditions>
                            <Setter Property="Template" Value="{StaticResource SelectedTemplate}" />
                        </MultiTrigger>
                    </Style.Triggers>
                </Style>
            </ListView.ItemContainerStyle>-->
        </ItemsControl>
    </Grid>
    <StackPanel VerticalAlignment="Bottom" HorizontalAlignment="Stretch" Orientation="Horizontal">
        <ComboBox x:Name="Baseforms"></ComboBox>
        <ComboBox x:Name="CrystalGroups"></ComboBox>
    </StackPanel>
</Grid>

背后的代碼(已更新)

    /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public static readonly DependencyProperty ShapesProperty = DependencyProperty.Register(
        "Shapes", typeof (ObservableCollection<Shape>), typeof (MainWindow),
        new PropertyMetadata(default(ObservableCollection<Shape>)));

    public ObservableCollection<Shape> Shapes
    {
        get { return (ObservableCollection<Shape>) GetValue(ShapesProperty); }
        set { SetValue(ShapesProperty, value); }
    }

    public ObservableCollection<string> Baselist = new ObservableCollection<string> {"a", "b", "c"};
    public ObservableCollection<string> Crystallist = new ObservableCollection<string>{"aa", "bb", "cc"};

public ObservableCollection<Shape> Shapelist = new ObservableCollection<Shape>();
    private SolidColorBrush _originalColorBrush = Brushes.Tomato;
    private SolidColorBrush _selectedColorBrush;
    private double _diameter;

    public MainWindow()
    {
        _diameter = 50d;
        this.ResizeMode = System.Windows.ResizeMode.CanMinimize;
        Shapes = new ObservableCollection<Shape>();
        InitializeComponent();
        InitializeLists(Baseforms, CrystalGroups);
    }

    private void InitializeLists(ComboBox Baseforms, ComboBox CrystalGroups)
    {
        Baseforms.ItemsSource = Baselist;
        CrystalGroups.ItemsSource = Crystallist;
        Shape Circle = new Ellipse();
        Circle.Stroke = System.Windows.Media.Brushes.Black;
        Circle.Fill = System.Windows.Media.Brushes.DarkBlue;
        Circle.HorizontalAlignment = HorizontalAlignment.Left;
        Circle.VerticalAlignment = VerticalAlignment.Center;
        Circle.Width = 50;
        Circle.Height = 50;
        Shapelist.Add(Circle);
    }


    private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        var inputElement = sender as IInputElement;
        if (inputElement == null) return;
        var point = e.GetPosition(inputElement);
        Shape shape = new Ellipse
        {
            Stroke = Brushes.Black,
            Fill = _originalColorBrush,
            Width = _diameter,
            Height = _diameter
        };
        var byX = point.X - _diameter / 2d;
        var byY = point.Y - _diameter / 2d;

        var existingShape = Shapes.FirstOrDefault(shapeToCheck =>
        {
            var data = shapeToCheck.Tag as ShapeDataPresentation;
            if (data == null) return false;
            var res = data.OriginalRectAroundShape.IntersectsWith(new Rect(point,point));
            return res;
        });

        if (existingShape == null)
        {
            var shapeDataPresentation = new ShapeDataPresentation { Name = string.Format("Ox:{0}, Oy:{1}", point.X.ToString("##.###"), point.Y.ToString("##.###")), OriginalRectAroundShape = new Rect(new Point(byX, byY), new Size(_diameter, _diameter)) };
            shape.Tag = shapeDataPresentation;
            shape.ToolTip = new ToolTip{Content = shapeDataPresentation.Name};
            var translateTransform = new TranslateTransform(byX, byY);
            shape.RenderTransform = translateTransform;
            Shapes.Add(shape);
        }
        else
        {
            if (DetailsList.SelectedItems.Contains(existingShape) == false)
            {
                DetailsList.SelectedItems.Clear();
                DetailsList.SelectedItems.Add(existingShape);
            }
        }


    }

    private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var currentSelected = e.AddedItems.OfType<Shape>().ToList();
        var prevSelected = e.RemovedItems.OfType<Shape>().ToList();
        if (currentSelected.Count > 0)
        {
            currentSelected.ForEach(shape =>
            {
                _selectedColorBrush = Brushes.CadetBlue;
                shape.Fill = _selectedColorBrush;
            });
        }
        if (prevSelected.Count > 0)
        {
            prevSelected.ForEach(shape =>
            {
                shape.Fill = _originalColorBrush;
            });
        }

    }
}

public class ShapeDataPresentation
{
    public string Name { get; set; }
    public Rect OriginalRectAroundShape { get; set; }
}

看起來怎么樣 這里

摘要:

  1. 在這里,您可以通過在畫布上單擊鼠標來創建項目,並通過代碼(UIElement_OnMouseDown)處理鼠標向下。
  2. 允許選擇和多重選擇,每次選擇時,都會以代碼(Selector_OnSelectionChanged)處理。

但是最好使用基於MVVM的方法在wpf中工作。

問候。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM