代码之家  ›  专栏  ›  技术社区  ›  Felix D.

在用户控件内公开控件的itemsource属性

  •  0
  • Felix D.  · 技术社区  · 8 年前

    我有一个包含一些按钮和列表视图的用户控件。

    我希望自定义控件具有 ItemsSource 直接绑定到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(M控制.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>
    

    myview模型.cs (设置为的数据源 MyWindow 仅包含 MyControl )

    public class MyViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<DocumentFile> DefaultList { get; set; }
    }
    

    调试时,不显示任何项,但视图模型中存在项。

    装订似乎是正确的。

    <custom:MyControl ItemsSource="{Binding DefaultList}" />
    

    这里怎么了?

    1 回复  |  直到 8 年前
        1
  •  2
  •   ASh aminescm    8 年前

    作为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。它怎么能把它们绑在一起?