[英]C# WPF Select UserControl on Canvas
我有一個帶有自定義UserControls的畫布。 現在,我希望能夠選擇它們,因為我想要一個顯示有關特定項目信息的屬性框。 當我單擊“畫布”中的UserControl時,可能會有一些好處,可以將SelectedItem屬性設置為該UserControl的viewmodel或更好的東西。 我只是不知道如何做好它,也沒有成功地使它以我為什么在這里問的任何方式起作用。
當前,我有一個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的基類,這些ViewModel是圍繞Model對象的簡單包裝。 我使用DataTemplates將它們綁定到View,所以沒有什么特別的地方。
那么,有沒有人對如何使這些控件具有可單擊性提出任何好的建議,以便我可以檢測到選擇了哪個控件,從而可以將其綁定到屬性框?
而不是使用ItemsControl
而是使用具有選擇的ListBox
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.