【问题标题】:C# WPF Select UserControl on CanvasC# WPF 在画布上选择用户控件
【发布时间】:2011-04-04 13:28:18
【问题描述】:

我有一个带有自定义用户控件的画布。现在我希望能够选择它们,因为我想要一个属性框来显示有关该特定项目的信息。当我单击 Canvas 中的 UserControl 时,如果能够将 SelectedItem 属性设置为该用户控件的视图模型或更好的东西,那就太好了。我只是不知道如何把它做好,也没有成功地让它以我在这里问的任何方式工作。

目前我有一个 DocumentViewModel,其中包含有关打开的文档/项目的信息。在这个视图模型中,我有一个组件列表,它们是在画布上表示的组件。这看起来像这样:

public class DocumentViewModel : BaseViewModel
{
        private ObservableCollection<ComponentViewModel> components;
        public ObservableCollection<ComponentViewModel> Components
        {
            get { return components; }
        }

        private string filePath;
        public string FilePath
        {
            get { return filePath; }
            set { filePath = value; }
        }

    ...
}

然后我有一个 DataTemplate 用于 DocumentViewModel 在视图中的外观。这看起来像这样:

<DataTemplate DataType="{x:Type ViewModels:DocumentViewModel}">
        <DataTemplate.Resources>
            <Converters:GuiSizeConverter x:Key="SizeConverter"/>
        </DataTemplate.Resources>
        <ItemsControl ItemsSource="{Binding Components}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas ClipToBounds="True" Height="{Binding CurrentProject.Height, Converter={StaticResource SizeConverter}}"
                            Width="{Binding CurrentProject.Width, Converter={StaticResource SizeConverter}}" 
                            HorizontalAlignment="Left" VerticalAlignment="Top">
                        <Canvas.Background>
                            <SolidColorBrush Color="{DynamicResource {x:Static SystemColors.WindowFrameColorKey}}"/>
                        </Canvas.Background>
                    </Canvas>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style>
                    <Setter Property="Utils:DraggableExtender.CanDrag" Value="True" />
                    <Setter Property="Canvas.Top" Value="{Binding Path=Y, Converter={StaticResource SizeConverter},Mode=TwoWay}" />
                    <Setter Property="Canvas.Left" Value="{Binding Path=X, Converter={StaticResource SizeConverter},Mode=TwoWay}" />
                </Style>
            </ItemsControl.ItemContainerStyle>
        </ItemsControl>
    </DataTemplate>

ComponentViewModel 是我的组件 ViewModel 的基类,它是我的 Model 对象的简单包装器。我使用 DataTemplates 将它们绑定到一个视图,所以没有什么特别的。

那么对于如何使这些控件可点击以便我可以检测选择了哪个控件以便我可以将其绑定到属性框有什么好的建议吗?

【问题讨论】:

    标签: c# wpf mvvm canvas itemscontrol


    【解决方案1】:

    不要使用ItemsControl,而是使用ListBox,它有选择。

    【讨论】:

    • 哈哈,就这么简单。非常感谢您的帮助,就像一个魅力。
    • 确实,很高兴它有帮助:)
    • 在切换到 ListBox 时我注意到的一件事是,我的拖动操作似乎真的很糟糕。例如,如果我将鼠标移动到快速并且指针超出控件它会停止并且我不能在拖动时将鼠标移到画布之外。知道 ItemsControl 和 ListBox 在这方面有什么不同吗?
    • 我不知道,对不起;我从未将这些控件与拖动等结合使用。
    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2011-05-20
    • 2017-07-21
    • 1970-01-01
    • 2016-02-28
    • 2010-11-26
    • 1970-01-01
    相关资源
    最近更新 更多