【问题标题】:Access bound object in UserControl code behind with DependencyProperty使用 DependencyProperty 访问 UserControl 代码中的绑定对象
【发布时间】:2011-03-31 19:20:49
【问题描述】:

我无法通过父 UserControl 上的数据绑定使用 DependencyProperty 设置自定义用户控件的属性。

这是我的自定义 UserControl 的代码:

public partial class UserEntityControl : UserControl
{
    public static readonly DependencyProperty EntityProperty =  DependencyProperty.Register("Entity",
        typeof(Entity), typeof(UserEntityControl));

    public Entity Entity
    {
        get
        {
            return (Entity)GetValue(EntityProperty);
        }
        set
        {
            SetValue(EntityProperty, value);
        }
    }

    public UserEntityControl()
    {
        InitializeComponent();
        PopulateWithEntities(this.Entity);
    }
}

我想访问后面代码中的 Entity 属性,因为这将根据存储在 Entity 中的值动态构建用户控件。我遇到的问题是 Entity 属性从未设置。

这是我在父用户控件中设置绑定的方式:

<ListBox Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding SearchResults}"     x:Name="SearchResults_List">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!--<views:SearchResult></views:SearchResult>-->
            <eb:UserEntityControl  Entity="{Binding}" ></eb:UserEntityControl>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我将 ListBox 的 ItemsSource 设置为 SearchResults,这是一个可观察的实体集合(与自定义 UserControl 上的实体类型相同)。

我在调试输出窗口中没有收到任何运行时绑定错误。我只是无法设置 Entity 属性的值。有什么想法吗?

【问题讨论】:

    标签: c# wpf data-binding dependency-properties


    【解决方案1】:

    您正在尝试使用 c-tor 中的 Entity 属性,这为时过早。在给出属性值之前,c-tor 将被解雇。

    你需要做的是向 DependencyProperty 添加一个 propertyChanged 事件处理程序,如下所示:

        public static readonly DependencyProperty EntityProperty = DependencyProperty.Register("Entity",
    typeof(Entity), typeof(UserEntityControl), new PropertyMetadata(null, EntityPropertyChanged));
    
        static void EntityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var myCustomControl = d as UserEntityControl;
    
            var entity = myCustomControl.Entity; // etc...
        }
    
        public Entity Entity
        {
            get
            {
                return (Entity)GetValue(EntityProperty);
            }
            set
            {
                SetValue(EntityProperty, value);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 2013-06-03
      • 2014-06-22
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      相关资源
      最近更新 更多