[英]Get name of clicked rectangle in WPF
我正在嘗試在WPF應用程序中獲取單擊的Rectangle的名稱。 我首先嘗試了這個:XAML:
<Canvas Width="1680" Height="800" MouseLeftButtonDown="canvas_MouseLeftButtonDown">
XAML.cs
private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
string selectedRect;
if (e.OriginalSource is Rectangle)
{
Rectangle ClickedRectangle = (Rectangle)e.OriginalSource;
var mouseWasDownOn = e.Source as FrameworkElement;
string elementName = mouseWasDownOn.Name;
selectedRect = elementName.ToString();
}
}
它運作良好,但是后來我不知道如何將selectedRect字符串傳遞給ViewModel,因此我嘗試將Relay命令從xaml直接傳遞給Viewmodel:
<UserControl x:Class="G.View.MapView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:extended="clr-namespace:G.ViewModel">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".7*" />
<ColumnDefinition Width=".3*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=".8*" />
<RowDefinition Height=".2*" />
</Grid.RowDefinitions>
<ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" Grid.Column="0" Grid.Row="0" Margin="10,10,0,0">
<ItemsControl ItemsSource="{Binding CaskList}" HorizontalAlignment="Left" VerticalAlignment="Top">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Width="1680" Height="800">
<Canvas.InputBindings>
<!-- One type of implementation -->
<KeyBinding Key="{Binding MouseLeftButtonDown.GestureKey}" Command="{Binding Path=HandleMyEvent}"/>
</Canvas.InputBindings>
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Rectangle Stroke="Black" Width="64" Height="64" Fill="{Binding Color}"></Rectangle>
<Label Content="{Binding ID}" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</UserControl>
它可以正常工作,當我單擊畫布時,我可以在方法中正確輸入,但是無法獲取矩形名稱,沒有事件MouseButtonEventArgs e。 你能幫助我嗎?
編輯:添加完整的XAML
嘗試這個:
private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
string selectedRect;
if (e.OriginalSource is Rectangle)
{
Rectangle ClickedRectangle = (Rectangle)e.OriginalSource;
var mouseWasDownOn = e.Source as FrameworkElement;
string elementName = mouseWasDownOn.Name;
selectedRect = elementName.ToString();
//ViewModel code
var vm = this.ViewModel as YourViewModel;
vm.RectangleName = elementName.ToString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.