我在通过父 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/