[英]UserControl with Dependency Property inside an ItemsControl: how to Bind element of ItemSource to x:Name of UserControl?
[英]Expose itemsource property of controls inside a usercontrol
我有一個用戶控件,其中包含一些按鈕和一個ListView。
我希望我的自定義控件具有ItemsSource
屬性,該屬性直接綁定到listviews itemsource。
MyControl.xaml.cs
public partial class MyControl : UserControl
{
public static DependencyProperty ItemsSourceProperty =
ListView.ItemsSourceProperty.AddOwner(typeof(AddFilesControl));
public ObservableCollection<DocumentFile> ItemsSource
{
get { return (ObservableCollection<DocumentFile>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
}
MyControl.xaml
<UserControl x:Class="[...].MyControls.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
<Grid>
<ListView>
<ListView.ItemTemplate>
[...]
</ListView.ItemTemplate>
</ListView>
</Grid>
</UserControl>
MyViewModel.cs (設置為僅包含MyControl
的MyWindow
的數據源)
public class MyViewModel : INotifyPropertyChanged
{
public ObservableCollection<DocumentFile> DefaultList { get; set; }
}
調試時不顯示任何項目,但ViewModel中有項目。
綁定似乎是正確的。
<custom:MyControl ItemsSource="{Binding DefaultList}" />
這是怎么了
作為MyControl一部分的ListView元素未連接到MyControl.ItemsSource
可以通過創建綁定來解決:
<UserControl x:Class="[...].MyControls.MyControl"
x:name="myControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
<Grid>
<ListView ItemsSource="{Binding ItemsSource, ElementName=myControl}">
</ListView>
</Grid>
</UserControl>
DP.AddOwner()
方法不會創建綁定。 ItemsSourceProperty
DP由ItemsControl類聲明。 AddOwner
不了解MyControl中的ListView。 如何將它們綁定在一起?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.