のオブジェクトを持つリスト へのItemsControl
バインドがあります。UI 要素 (つまり、楕円) をクリックすると、オブジェクトを取得したいと考えています。MyItems
SomeType
SomeType
これは機能しません:
public HitTestResultBehavior SomeTypeHitCallback(HitTestResult result)
{
if (result.VisualHit is Ellipse)
{
var ellipse = result.VisualHit as Ellipse;
// Does not work...
object item = itemsSource.ItemContainerGenerator.ItemFromContainer(ellipse);
// item now equals DependencyProperty.UnsetValue
// Here I want to change the property of the object
// associated with the Ellipse...
var o = item as SomeType;
o.IsSelected = !o.IsSelected;
return HitTestResultBehavior.Continue;
}
return HitTestResultBehavior.Stop;
}
private void Canvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var pt = e.GetPosition((UIElement)sender);
VisualTreeHelper.HitTest(
(UIElement)sender,
null,
new HitTestResultCallback(SomeTypeHitCallback),
new PointHitTestParameters(pt));
}
XAML は次のとおりです。
<ItemsControl x:Name="itemsSource" ItemsSource="{Binding Path=MyItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas ClipToBounds="True" PreviewMouseLeftButtonDown="Canvas_PreviewMouseLeftButtonDown" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Ellipse x:Name="item" Width="{Binding Width}" Height="{Binding Height}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
SomeType
どうすればオブジェクトを見つけることができますか?