Как привязать свойство элемента к свойству объекта на уровень выше?

Рейтинг: 0Ответов: 1Опубликовано: 29.03.2023

Пытаюсь выполнить привязку ItemsControl к списку, который содержит ViewModel, таким образом, что некоторые свойства элементов в ItemsControl привязывались бы не к свойству объекта списка, а к свойству самой ViewModel.

View model:

class AnnotationsViewModel
{
   public ObservableCollection<Annotation> Annotations {get; set;} = new ();
   public double Radius {get; set;} = 10.0;
}

Annotation:

class Annotation
{
   public double Top {get; set;}
   public double Left {get; set;}
   public string Name {get; set;} = string.Empty;
}

Далее в XAML:

<ItemsControl ItemsSource="{Binding Path=Annotations}"

  <ItemsControl.ItemsPanel>
    <Canvas/>
  </ItemsControl.ItemsPanel>

  <ItemsControl.ItemContainerStyle>
     <Style TargtType="ContentPresenter">
         <Setter Ptoperty="Canvas.Top" Value="{Binding Top}"/>
         <Setter Ptoperty="Canvas.Left" Value="{Binding Left}"/>
     </Style>
  </ItemsControl.ItemContainerStyle>

  <ItemsControl.ItemTemplate>
     <DataTemplate>
         <StackPanel>
            <Ellipse Width="{Binding Path=Radius}"
                     Height="{Binding Path=Radius}"
                     Fill="Black"/>
            <TextBlock Text="{Binding Path=Name}"/>
         </StackPanel>
     </DataTemplate>
  </ItemsControl.ItemTemplate>

</ItemsControl>

Я хотел бы привязать ширину эллипса к свойству Radius самой model view, вместо того, чтобы в классе Annotation определять это свойство.

Заранее благодарен.

Ответы

▲ 0Принят

Используйте RelativeSource

<Ellipse Width="{Binding DataContext.Radius, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
         Height="{Binding DataContext.Radius, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
         Fill="Black"/>

Или так

<Ellipse DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
         Width="{Binding Radius}"
         Height="{Binding Radius}"
         Fill="Black"/>