C# WPF Select UserControl on Canvas
I have a Canvas with custom UserControls in it. Now I want to be able to have them selectable since I want to have a properties box which shows information about that specific item. What would be nice would be to have something along the way of when I click on a UserControl in the Canvas a SelectedItem property could be set to the viewmodel of that usercontrol or something better. I just have no clue how to do it good nor have I been successful in making it work in any way that why i'm asking here.
Currently I have a DocumentViewModel which holds information about the open document/project. In this viewmodel I have a list of components, which are the ones being represented on the canvas. This looks something like this:
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; }
}
...
}
Then I have a DataTemplate for how the DocumentViewModel should look in the View. This looks like this:
<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>
The ComponentViewModel is a base class for my component ViewModels which are simple wrappers around my Model objects. The I use DataTemplates to bind them to a View so nothing special there.
So does anyone have any good suggestions for how to make these controls clickable so i can detect which one is selected so 开发者_如何学JAVAi can bind that to a properties box?
Instead of using an ItemsControl
just use a ListBox
, which has selection.
精彩评论