UserControl中的依赖属性List <string>

Jim*_*mmy 6 c# wpf dependency-properties

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

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


}
Run Code Online (Sandbox Code Playgroud)

我试图在另一个用户控件中使用此usercontrol在不同的程序集中,如下所示

    <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>
Run Code Online (Sandbox Code Playgroud)

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

Dr.*_*ABT 6

据我所知,WPF可能不会直接调用你的属性的setter,如果它暴露了DependencyProperty.相反,它可以DependencyProperty直接设置.有关更多信息,请参阅MSDN上的依赖项属性概述.特别是这部分:

依赖属性可能在多个位置"设置"
以下是示例XAML,其中相同的属性(背景)具有可能影响值的三个不同的"设置"操作...

要测试是否在您的示例中发生了这种情况(加上获取可以对设置值进行操作的通知),您可以尝试在 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();
    }
} 
Run Code Online (Sandbox Code Playgroud)