2011-04-04 121 views
1

我有一個自定義UserControls的Canvas。現在我希望能夠讓他們可選擇,因爲我想有一個屬性框顯示有關該特定項目的信息。有什麼好的做法是,當我點擊畫布上的UserControl時,可以將該屬性設置爲該用戶控件的視圖模型或更好的東西。我完全不知道如何做到這一點,也不知道爲什麼我在這裏問這個問題。C#WPF在畫布上選擇UserControl

目前我有一個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是我的組件ViewModels的基類,它是我的Model對象的簡單包裝。我使用DataTemplates將它們綁定到一個視圖,所以沒什麼特別的。

因此,沒有人有如何使這些控件可點擊的好建議,所以我可以檢測哪一個被選中,所以我可以將它綁定到屬性框?

回答

1

而不是使用ItemsControl只是使用ListBox,它有選擇。

+0

哈哈,那很簡單。非常感謝幫助,像魅力一樣工作。 – chiefi 2011-04-04 14:54:10

+0

確實,很高興它幫助:) – 2011-04-04 15:03:50

+0

有一件事我注意到,但當轉換到ListBox時,我的拖動似乎工作非常糟糕。例如,如果我將鼠標移動到快速並且指針超出控制範圍,它將停止,並且拖動時我無法將鼠標移到畫布外。任何想到ItemsControl和ListBox之間有什麼不同之處? – chiefi 2011-04-04 15:39:41