1

我得到了一个自定义控件,其中包含一个 ProgressBar 以及其他元素。

<ProgressBar Value="{TemplateBinding CurrentProgress}"
             MinValue="{TemplateBinding MinValue}"
             MaxValue="{TemplateBinding MaxValue}"/>

<Label Content="{TemplateBinding CurrentProgress}"/>

在我的 .cs 文件中,我定义了所有这些属性,如下所示:

#region MaxProgress
public int MaxProgress
{
    get { return (int)GetValue(MaxProgressProperty); }
    set { SetValue(MaxProgressProperty, value); }
}

public static readonly DependencyProperty MaxProgressProperty =
        DependencyProperty.Register("MaxProgress", typeof(int), typeof(GameFlowControl), new FrameworkPropertyMetadata(1000, FrameworkPropertyMetadataOptions.AffectsRender)); 
#endregion

#region CurrentProgress
public int CurrentProgress
{
    get { return (int)GetValue(CurrentProgressProperty); }
    set { SetValue(CurrentProgressProperty, value); }
}

public static readonly DependencyProperty CurrentProgressProperty =
    DependencyProperty.Register("CurrentProgress", typeof(int), typeof(GameFlowControl), new FrameworkPropertyMetadata(50, FrameworkPropertyMetadataOptions.AffectsRender)); 
#endregion

#region MinProgress
public int MinProgress
{
    get { return (int)GetValue(MinProgressProperty); }
    set { SetValue(MinProgressProperty, value); }
}

public static readonly DependencyProperty MinProgressProperty =
    DependencyProperty.Register("MinProgress", typeof(int), typeof(GameFlowControl), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));
#endregion

如上所示将这些值绑定到标签可以正常工作,但显然这些绑定不适用于我的 ProgressBar。到目前为止我已经尝试过:

  • 更改 Value、MinValue 和 MaxValue 的顺序。
  • 在 TemplateBinding 中添加了一个错字(例如 CurrentProgress XYZ),这给了我一个编译错误(因此可以识别属性)
  • 为属性添加了默认值(请参阅 0、50、1000)。
  • 直接删除了绑定和设置值:Value = 50, MinValue = 0, MaxValue=100,这显示 ProgressBar 显示为半填充。
  • 为这些属性的 getter 添加了断点,它们没有被触发(这让我很困惑!)

任何提示可能导致这种情况?

4

1 回答 1

2

根据你的问题回答

在这种情况下您应该使用的绑定方法是Value="{Binding CurrentProgress, RelativeSource={RelativeSource AncestorType={x:Type GameFlowControl}}}". 这会向上遍历可视化树,找到第一个GameFlowControl控件,然后从该相对位置绑定到路径。

替代

作为替代方案,如果您没有将DataContextinUserControl用于任何其他目的,您可以使用较短的绑定方法。

首先,您需要使用以下内容将 分配DataContext给派生UserControl引用:-

    public GasFlowControl()
    {
        InitializeComponent();

        DataContext = this;  //Set the DataContext to point to the control itself

    }

然后您的绑定可以简化为:-

    <ProgressBar Value="{Binding CurrentProgress}"
         MinValue="{Binding MinValue}"
         MaxValue="{Binding MaxValue}"/>

    <Label Content="{Binding CurrentProgress}"/>

回答你的困惑

为这些属性的 getter 添加了断点,它们没有被触发(这让我很困惑!)

您没有为属性 Getters 和 Setters 触发任何断点的原因是 WPF 框架不使用它们。GetValue(CurrentProgressProperty);它在内部直接调用SetValue(CurrentProgressProperty, value);。它们只是为了方便您将其包含在您的代码中,并方便进行类型转换,从而在编译时进行类型检查。

如果您的代码不使用它们,那么它们将永远不会被调用。

于 2016-01-15T10:58:55.927 回答