c# - 在用户控件中公开控件的 itemsource 属性

标签 c# wpf listview mvvm binding

我有一个包含一些按钮和一个 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/

相关文章:

wpf usercontrol,将按钮的命令参数绑定(bind)到父用户控件

android - 带有图像和两个项目的 ListView ?

Android listview,显示列表的用户末尾,然后自动滚动到顶部

c# - 为我的应用程序制作帮助文件

c# - 如何使用其名称调用方法?

c# - 删除子域的cookie

android listview 第一个可见位置

c# - 如何在 C# 中更改 DataGridViewComboBoxColumn 的行为?

c# - MVVM+ WPF PopUp 打不开

WPF - 如何设计包含角落标签的边框