0

のオブジェクトを持つリスト へのItemsControlバインドがあります。UI 要素 (つまり、楕円) をクリックすると、オブジェクトを取得したいと考えています。MyItemsSomeTypeSomeType

これは機能しません:

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どうすればオブジェクトを見つけることができますか?

4

1 に答える 1

1

itemsSource.ItemContainerGenerator.ItemFromContainerを渡した場合にのみ機能しますがItem Container、その視覚要素は機能しません。ContentPresenterそのため、Ellipse を含むものを見つけて、それを引数としてItemFromContainerメソッドに渡す必要があります。ItemsContainerforItemsControlContentPresenterです。

VisualHit私が見る 1 つの方法は、 から が見つかるまで親のそばに行き、そのアイテムContentPresenterを呼び出すことです。ItemFromContainerこれを試してください、うまくいくはずです。しかし、ここでの問題は、ItemsContainer のテンプレート内に ContentPresenter が存在する可能性があり、null が再び取得されることです。確かに に変更ItemsControlするListBoxと を見つけやすくなりますListBoxItemが、スタイルを変更し、不要な追加機能を削除する必要があります。

また、確認してみてくださいEllipse.DataContext。私はまさにあなたが望むものである可能性があります

于 2012-11-29T13:18:19.670 に答える