c# - 使用 DependencyProperty 访问 UserControl 代码中的绑定(bind)对象

标签 c# wpf data-binding dependency-properties

我在通过父 UserControl 上的数据绑定(bind)使用 DependencyProperty 设置自定义用户控件的属性时遇到问题。

这是我的自定义用户控件的代码:

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 属性从未设置。

以下是我在父用户控件中设置绑定(bind)的方法:

<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 上的实体类型相同)。

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

最佳答案

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

您需要做的是将 propertyChanged 事件 HAndler 添加到 DependencyProperty,如下所示:

    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);
        }
    }

关于c# - 使用 DependencyProperty 访问 UserControl 代码中的绑定(bind)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5505119/

相关文章:

c# - 将位图数据提取到字节数组

c# - Visual Studio 2012 Express 调试 explorer.exe - 没有命中断点

.net - XAML 相当于 HTML 中的 DIV?

c# - StackPanel.ActualHeight 始终为零

wpf - 自定义控件的内容无法绑定(bind)到控件的父级

javascript - 在另一个函数中使用模板生成的 id 吗?

c# - 使用 include 不会改变行为

wpf - 按钮不覆盖父级的 IsEnabled

c# - 我觉得自己像个管道厂里的老鼠。设计 WPF 绑定(bind)解决方案的策略?

c# - 从 asp.net 调用 Web 服务会导致异常但从 Windows 应用程序不会?