【问题标题】:Dependency property List<string> in UserControlUserControl 中的依赖属性 List<string>
【发布时间】:2012-01-20 15:15:39
【问题描述】:

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

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 绑定的更多信息,请参阅here

标签: c# wpf dependency-properties


【解决方案1】:

据我所知,如果 WPF 公开了DependencyProperty,它可能不会直接调用您的属性的设置器。相反,它可以直接设置DependencyProperty。有关详细信息,请参阅Dependency Properties Overview on 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();
    }
} 

【讨论】:

  • @Andrew- 那是正确的。非常感谢。不知道WPF会直接调用依赖属性。
  • 嗨,吉米,没问题。您格式良好的问题可以轻松回答。另一个 WPF 陷阱! :)
【解决方案2】:

您尚未指定绑定模式。也许它默认为单向? 试试看:{Binding Path=CheckList, Mode=TwoWay}

【讨论】:

    猜你喜欢
    • 2015-03-19
    • 1970-01-01
    • 2017-12-24
    • 2019-12-08
    • 2014-08-31
    • 1970-01-01
    • 2017-12-18
    • 2023-04-07
    • 2014-04-10
    相关资源
    最近更新 更多