[UWP如何在不改变ListView绑定源的情况下获得放置在ListView中的UserControl的控制?<



我已经在ListView中放置了一个UserControl。

如何在视图中获得这个UserControl的控制

如果我把它放在ListView中,我无法在视图中访问它。我也不希望对listView绑定源做任何更改。

它的名称不能在视图中直接访问。

我可以访问事件,但不能访问属性(x:Name, Visibility等)。

你可以使用VisualTreeHelper类来获取你的UserControl .

  1. 通过调用ListView的ContainerFromItem或ContainerFromIndex获取每个ListViewItem。

  2. 创建一个递归函数来查找每个ListViewItem中作为UserControl的DependencyObjects

我做了一个简单的例子来展示它是如何工作的。您可以参考以下代码:

MainPage.xaml

<Grid>
<ListView x:Name="MyListView" Margin="0,0,0,109">
<ListView.ItemTemplate>
<DataTemplate x:DataType="x:String">
<Grid>
<local:MyUserControl1></local:MyUserControl1>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Content="Button" Margin="682,943,0,0" VerticalAlignment="Top" Click="Button_Click"/>
</Grid>

MainPage.cs

public List<string> ItemsSourceList { get; set; }
public MainPage()
{
this.InitializeComponent();
ItemsSourceList = new List<string>();
ItemsSourceList.Add("1");
ItemsSourceList.Add("2");
ItemsSourceList.Add("3");
ItemsSourceList.Add("4");
ItemsSourceList.Add("5");
MyListView.ItemsSource = ItemsSourceList;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (var strItem in ItemsSourceList)
{
// get every listview item first
ListViewItem item = MyListView.ContainerFromItem(strItem) as ListViewItem;
// the DependencyObject is the UserControl that you want to get                
DependencyObject myUserControl = FindChild(item);
}
}
public DependencyObject FindChild(DependencyObject parant)
{
int count = VisualTreeHelper.GetChildrenCount(parant);
for (int i = 0; i < count; i++)
{
var MyChild = VisualTreeHelper.GetChild(parant, i);
if (MyChild is MyUserControl1)
{
//Here can get the MyUserControl1. 

MyUserControl1 myUserControl = (MyUserControl1)MyChild;
myUserControl.Foreground = new SolidColorBrush(Colors.Red);
return myUserControl;
}
else
{
var res = FindChild(MyChild);
return res;
}
}
return null;
}

最新更新