gpt4 book ai didi

c# - UserControl 中的依赖属性 List

转载 作者:太空狗 更新时间:2023-10-29 21:35:40 27 4
gpt4 key购买 nike

我的点网程序集中的用户控件中有一个依赖属性(字符串列表),如下所示

public partial class ItemSelectionUserControl : UserControl
{
public List<string> AvailableItems
{
get { return (List<string>)this.GetValue(AvailableItemsProperty); }
set { this.SetValue(AvailableItemsProperty, value); }
}
public static readonly DependencyProperty AvailableItemsProperty = DependencyProperty.Register(
"AvailableItems", typeof(List<string>), typeof(ItemSelectionUserControl), new FrameworkPropertyMetadata{BindsTwoWayByDefault =true});


public ItemSelectionUserControl()
{
InitializeComponent();
}


}

我正在尝试在另一个程序集中的另一个用户控件中使用此用户控件,如下所示

    <UserControl 
xmlns:ctrl="clr-namespace:HH.Windows.UserControls;assembly=HH.Windows.UserControls"
/>

// .....
<Grid>
<ctrl:ItemSelectionUserControl Grid.Column="0" Grid.Row="3" Grid.ColumnSpan="3" AvailableItems="{Binding Path=CheckList}"/>
</Grid>

我可以看到正在调用 CheckList 的 get 访问器,但它没有设置依赖属性“AvailableItems”。 “AvailableItems”集合中的断点永远不会被调用。我做错了什么?

最佳答案

据我所知,如果 WPF 公开了 DependencyProperty,它可能不会直接调用您的属性的 setter。相反,它可以直接设置 DependencyProperty。有关详细信息,请参阅 Dependency Properties Overview on MSDN .特别是本节:

Dependency Properties Might Be "Set" in Multiple Places
The following is example XAML where the same property (Background) has three different "set" operations that might influence the value ...

要测试您的示例中是否发生这种情况(并获得可以对设置值进行操作的通知),您可以尝试在 FrameworkPropertyMetadata

中添加回调

例如

public partial class ItemSelectionUserControl : UserControl 
{
public List<string> AvailableItems
{
get { return (List<string>)this.GetValue(AvailableItemsProperty); }
set { this.SetValue(AvailableItemsProperty, value); }
}

public static readonly DependencyProperty AvailableItemsProperty =
DependencyProperty.Register("AvailableItems",
typeof(List<string>), typeof(ItemSelectionUserControl),
new FrameworkPropertyMetadata(OnAvailableItemsChanged)
{
BindsTwoWayByDefault =true
});

public ItemSelectionUserControl()
{
InitializeComponent();
}

public static void OnAvailableItemsChanged(
DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
// Breakpoint here to see if the new value is being set
var newValue = e.NewValue;
Debugger.Break();
}
}

关于c# - UserControl 中的依赖属性 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8943576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com