我有一个包含一些按钮和一个 ListView 的用户控件。
我希望我的自定义控件具有 ItemsSource
直接绑定(bind)到 ListView 项目源的属性。
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 (设置为
MyWindow
的 DataSource 仅包含 MyControl
)public class MyViewModel : INotifyPropertyChanged
{
public ObservableCollection<DocumentFile> DefaultList { get; set; }
}
调试时不显示任何项目,但 ViewModel 中有项目。
绑定(bind)似乎是正确的。
<custom:MyControl ItemsSource="{Binding DefaultList}" />
这里有什么问题?
最佳答案
作为 MyControl 一部分的 ListView 元素未连接到 MyControl.ItemsSource
可以通过创建绑定(bind)来修复:
<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()
方法不会创建绑定(bind)。 ItemsSourceProperty
DP 由 ItemsControl 类声明。 AddOwner
不知道 MyControl 中的 ListView。怎么能把他们绑在一起?
关于c# - 在用户控件中公开控件的 itemsource 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50566210/