我有一個頁面,其中包含一個 ListView x:系結到我的 ViewModel 中的一個物件。此物件包含一個物件串列(時間戳),其中包含一個主題串列,其中包含另一個物件的串列。我在 2 個串列視圖中呈現資料,一個在另一個串列視圖中。
<ListView
x:Name="primaryList" // for exemplification purposes
ItemsSource="{x:Bind ViewModel.VideoProject.TimeStamps, Mode=OneWay}"
ItemClick='{x:Bind ViewModel.ListViewTimeStamps_ItemClick, Mode=OneWay}'>
ListView 包含另一個 ListView 的 DataTemplate
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Spacing="5">
<TextBlock Text="{Binding Id}"
FontSize="15"
HorizontalAlignment="Left"
FontWeight="Bold" />
<ListView ItemsSource="{Binding Subjects}"
x:Name="secondaryList"
SelectionMode="Multiple">
<ListView.ItemTemplate>
....
第二個 ListView 后面跟著另一個相同的結構。
我的目標是將第二個 ListView ItemClickEvent 系結到我的 ViewModel 中的 ListViewTimeStamps_ItemClick 方法,因為我需要secondaryListView 持有的物件(主題)中包含的資料。我可以嘗試將資料模板背景關系設定為 ViewModel,但它會破壞主題系結。
我發現了很多關于這個主題的問題,但與 WPF 不同的是,沒有 AncestorType 來獲取向上的樹參考。
Obs:我的專案基于模板模型,它創建了 XAML .cs??,并將 ViewModel 作為屬性。我也沒有在 XAML 頁面上設定 DataContext,因為我可以 x:bind 通常將我的視圖模型系結到頁面元素而無需顯式設定。
有沒有辦法在不使用附加屬性的情況下完成?謝謝你。
uj5u.com熱心網友回復:
由于不支持在 WinUI 中設定AncestorTypea 的屬性RelativeSource,因此如果不撰寫一些代碼,就無法在純 XAML 中完成此操作。
您可以按照此處的建議和示例實施附加的行為:
public static class AncestorSource
{
public static readonly DependencyProperty AncestorTypeProperty =
DependencyProperty.RegisterAttached(
"AncestorType",
typeof(Type),
typeof(AncestorSource),
new PropertyMetadata(default(Type), OnAncestorTypeChanged)
);
public static void SetAncestorType(FrameworkElement element, Type value) =>
element.SetValue(AncestorTypeProperty, value);
public static Type GetAncestorType(FrameworkElement element) =>
(Type)element.GetValue(AncestorTypeProperty);
private static void OnAncestorTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement target = (FrameworkElement)d;
if (target.IsLoaded)
SetDataContext(target);
else
target.Loaded = OnTargetLoaded;
}
private static void OnTargetLoaded(object sender, RoutedEventArgs e)
{
FrameworkElement target = (FrameworkElement)sender;
target.Loaded -= OnTargetLoaded;
SetDataContext(target);
}
private static void SetDataContext(FrameworkElement target)
{
Type ancestorType = GetAncestorType(target);
if (ancestorType != null)
target.DataContext = FindParent(target, ancestorType);
}
private static object FindParent(DependencyObject dependencyObject, Type ancestorType)
{
DependencyObject parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null)
return null;
if (ancestorType.IsAssignableFrom(parent.GetType()))
return parent;
return FindParent(parent, ancestorType);
}
}
所以到目前為止還沒有替代 AncestorType?
不,不在 XAML 中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/461938.html
上一篇:屬性值更改時更改影像源
