【问题标题】:Dependency property in datatemplate not updating数据模板中的依赖属性未更新
【发布时间】:2014-12-29 14:59:29
【问题描述】:

我们有一个自定义控件,它有两个依赖属性,Round 和 Depth。问题是当我在数据模板中使用该控件时:

<DataTemplate x:Key="SyntDom" DataType="{x:Type entities:SwapInstrument}" >
...
    <depthOfMarket:DOMControl Grid.Row="1" Instrument="{Binding}" Margin="10,5" Round="False" Depth="38">
...
</DataTemplate>
....
<ContentControl ContentTemplate="{StaticResource SyntDom}" Content="{Binding Instruments.Instrument1}"/>

然后 Round 属性永远不会更新为 False 值,而 Depth 得到它的 38。 当我直接使用 DOMControl 而不用 ContentControl 包装它时,它可以正常工作。

控制中这些属性的代码几乎是复制粘贴,所以我怀疑是否存在问题。

更新:依赖属性定义

public static readonly DependencyProperty DepthProperty = DependencyProperty.Register("Depth", typeof (int), typeof (DOMControl), new PropertyMetadata(OnChangedDepth));
public int Depth
{
    get { return (int) GetValue(DepthProperty); }
    set { SetValue(DepthProperty, value); }
}

private static void OnChangedDepth(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
    ((DOMControl) obj).OnChangedDepth();
}

private void OnChangedDepth()
{
    _dom.Depth = Depth;
    BindGrid();
}

public static readonly DependencyProperty RoundProperty = DependencyProperty.Register("Round", typeof (bool), typeof (DOMControl), new PropertyMetadata(OnChangedRound));

public bool Round
{
    get { return (bool) GetValue(RoundProperty); }
    set { SetValue(RoundProperty, value); }
}

private static void OnChangedRound(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
    ((DOMControl) obj).OnChangedRound();
}

private void OnChangedRound()
{
    _converterVolume.Round = Round;
}

【问题讨论】:

  • 你是什么意思“更新为假值? Does that mean updated is True”?
  • 我的意思是当我调试它时,我可以看到控件的 Round 属性设置为 true (我猜它是在最初在表单上创建控件时),但它永远不会得到我的 False 值放入 xaml。
  • 请向我们展示您的 DP 声明。
  • 哦,在控件构造函数中 Round 设置为 true。但尽管如此,它从未设置为 False。

标签: wpf datatemplate


【解决方案1】:

所以我将 Round 属性定义为

public static readonly DependencyProperty RoundProperty = 
    DependencyProperty.Register("Round", typeof (bool), typeof (DOMControl), 
          new PropertyMetadata(OnChangedRound));

我已经改成

public static readonly DependencyProperty RoundProperty = 
    DependencyProperty.Register("Round", typeof (bool), typeof (DOMControl), 
          new PropertyMetadata(true, OnChangedRound));

即为属性定义了一个默认值,现在可以正常工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多