【问题标题】:update binding dependency property更新绑定依赖属性
【发布时间】:2017-03-14 14:32:21
【问题描述】:

我有一个自定义用户控件,我必须对其进行扩展以添加几个新元素。在这个控件中,我已经有几个属性是这样的:

public static readonly DependencyProperty CountProperty =
        DependencyProperty.Register("CountProperty ", typeof(int), typeof(SomeThirdPartyControl), new PropertyMetadata(0));

    public int Count
    {
        get { return (int)GetValue(CountProperty ); }
        set
        {
            SetValue(CountProperty, value);
        }
    }

并添加了这样的几个项目

var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
            textBlockFactory.SetValue(TextBlock.TextProperty, new Binding(nameof(Count)));

我还有一个更新方法,基本上就是这样:

Count = items.Count;

当计数更新时,我希望 UI 会更新。但是,textBlockFactory 中的值似乎永远不会更新。

如何确保在更改依赖项属性时更新 FrameworkElement 值。

【问题讨论】:

  • "绑定似乎永远不会更新" - 哪个绑定? “每当该值更新时” - 它在哪里更新?您能否将这两点都添加到问题中(完整的类、完整的方法等)?
  • 试试是否可行:new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
  • 最终您可以在 DependencyProperty 更新时使用 PropertyChangedCallback 执行某些操作。请进一步澄清您的问题。什么不完全有效?
  • 我可以使用 propertychangedCallback 但是在那个回调方法中我如何访问 frameworkelement 值来改变它?

标签: c# xaml dependency-properties


【解决方案1】:

尝试将您的 DependencyProperty 设置为默认绑定 TwoWay,就像@Arie 说的那样:

类似这样的:

        public int Count
        {
            get { return (int)GetValue(CountProperty); }
            set { SetValue(CountProperty , value); }
        }

        public static readonly DependencyProperty CountProperty =
            DependencyProperty.Register("Count" , typeof(int) , 
                typeof(SomeThirdPartyControl) ,
                  new FrameworkPropertyMetadata(0 ,
                       FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

【讨论】:

    猜你喜欢
    • 2011-12-18
    • 2011-03-05
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2012-11-08
    • 2012-08-01
    相关资源
    最近更新 更多