Вместо того, чтобы перемещаться по визуальному дереву с помощью FindAncestor
, вы можете пересечь DataContext
вашего текущего элемента управления. Чтобы это сделать, вам нужна ссылка в вашем ViewModels
родительскому ViewModel
. У меня обычно есть базовый ViewModel
класс, который имеет свойство Parent
и Root
:
public abstract class ViewModel : INotifyPropertyChanged
{
private ViewModel parentViewModel;
public ViewModel(ViewModel parent)
{
parentViewModel = parent;
}
/// <summary>
/// Get the top ViewModel for binding (eg Root.IsEnabled)
/// </summary>
public ViewModel Root
{
get
{
if (parentViewModel != null)
{
return parentViewModel.Root;
}
else
{
return this;
}
}
}
}
В XAML, вы можете заменить это:
<ComboBox x:Name="Sector"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.SectorList}"
SelectedValuePath="Id"
SelectedValue="{Binding SectorId, Mode=TwoWay}" />
К этому:
<ComboBox x:Name="Sector"
ItemsSource="{Binding Root.SectorList}"
SelectedValuePath="Id"
SelectedValue="{Binding SectorId, Mode=TwoWay}" />
One требование: свойства Root
всегда должны существовать в самом верхнем ViewModel
.
Я думаю, что FindAncestor - это путь, потому что ListBoxItems имеют свой собственный DataContext. Как это дает проблемы с производительностью? –