Binding to a dependency property of a user control WPF/XAML

前端 未结 4 1014
广开言路
广开言路 2021-02-07 10:08

My app looks like this:


SectionHeader

SectionHeader

Content

SectionHeader

Conte

4条回答
  •  清歌不尽
    2021-02-07 10:48

    Having tried to repro this from your description and coming across a similar problem I found that the only way I could make it work is to not set the DataContext of the UserControl, and instead use ElementBinding:

    
        
            
            
            
    
        
    
    

    The implementation of this UC is trivially simple:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Collections.ObjectModel;
    using System.Collections;
    
    namespace WpfApplication2
    {
        /// 
        /// Interaction logic for UserControl1.xaml
        /// 
        public partial class UserControl1 : UserControl
        {
            public IEnumerable UCApps
            {
                get { return (IEnumerable)GetValue(UCAppsProperty); }
                set { SetValue(UCAppsProperty, value); }
            }
    
            // Using a DependencyProperty as the backing store for Apps.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty UCAppsProperty =
                DependencyProperty.Register("UCApps", typeof(IEnumerable), typeof(UserControl1), new UIPropertyMetadata(null));
    
            public UserControl1()
            {
                InitializeComponent();            
            }
        }
    }
    

    as is the XAML that calls it:

    
        
    
    

    (I changed the name of Apps in your Usercontrol to UCApps so I could see what was going on - too many properties with the same name got confusing!)

提交回复
热议问题