从依赖属性生成自定义项控件作为 UserControl 中的项源

我正在制作一个 UserControl 以从依赖项属性生成附加文件列表作为 ItemSource。但 ItemSource (DependencyProperty) 计数为 0。我尝试调试并意识到 ViewModel 中的 ObservableCollection 是在 UserControl 的构造函数初始化后绑定的。


我正在以 MVVM 模式进行编码,我创建了一个函数来为 ViewModel 中的 ObservableCollection 准备一些示例数据,并在 MainWindow 内将 UserControl 的 DataContext 与该 ViewModel 绑定,然后为 ObservableCollection 设置 ItemSource


我的 ViewModel 代码隐藏:


//The properties

  ObservableCollection<FileAttachmentModel> filesAttachment;

        public ObservableCollection<FileAttachmentModel> FilesAttachment

        {

            get { return filesAttachment; }

            set { filesAttachment = value; OnPropertyChanged("FilesAttachment"); }

        }

//The function prepare sample data

 private ObservableCollection<FileAttachmentModel> PrepareData()

        {

            FilesAttachment.Add(new FileAttachmentModel() { FileName = "TrackA", FilePath = "D:\trackA.png" });

            FilesAttachment.Add(new FileAttachmentModel() { FileName = "TrackB", FilePath = "D:\trackB.png" });

            FilesAttachment.Add(new FileAttachmentModel() { FileName = "TrackC", FilePath = "D:\trackC.png" });


        }

我的用户控件 xaml:


<UserControl x:Class="MailSender.Controls.FileAttachment.FileAttachment"

             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" 

             xmlns:local="clr-namespace:MailSender.Controls.FileAttachment"            

             mc:Ignorable="d" 

             d:DesignHeight="450" d:DesignWidth="800"

              DataContext="{Binding RelativeSource={RelativeSource Self}}"

             Name="fileAttachmentUC"

             >

使用中:


<control:FileAttachment DataContext="{StaticResource vmMainWindow}" ItemSource="{Binding FilesAttachment,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

我期望的是为附加文件制作一个容器,例如 Microsoft 的 Outlook。请帮忙!提前致谢!


慕雪6442864
浏览 78回答 1
1回答

慕姐8265434

GenerateFileItem每当使用以下方法设置依赖项属性时,您都应该调用PropertyChangedCallback:public static readonly DependencyProperty ItemSourceProperty = DependencyProperty.Register("ItemSource",&nbsp; &nbsp; typeof(ObservableCollection<FileAttachmentModel>), typeof(FileAttachment), new PropertyMetadata(new PropertyChangedCallback(OnChanged));//the wrapper propertypublic ObservableCollection<FileAttachmentModel> ItemSource{&nbsp; &nbsp; get { return (ObservableCollection<FileAttachmentModel>)GetValue(ItemSourceProperty); }&nbsp; &nbsp; set { SetValue(ItemSourceProperty, value); }}private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){&nbsp; &nbsp; FileAttachment fa = (FileAttachment)d;&nbsp; &nbsp; fa.GenerateFileItem(fa.ItemSource);}在初始化ItemSource之前无法设置该属性。UserControl
打开App,查看更多内容
随时随地看视频慕课网APP