自定义控件中的绑定进度条似乎不起作用
本文关键字:不起作用 绑定 自定义控件 | 更新日期: 2023-09-27 18:30:27
>我得到了一个自定义控件,其中包含一个进度条以及其他元素。
<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
如上所示将这些值绑定到标签工作正常,但显然这些绑定不适用于我的进度条。到目前为止我尝试过:
- 更改值、最小值和最大值的顺序。
- 在模板绑定中添加了一个拼写错误(如CurrentProgressXYZ),这给了我一个编译错误(因此可以识别属性)
- 向"属性"添加了默认值(请参阅 0、50、1000)。
- 直接删除了绑定和设置值:值 = 50,最小值 = 0,最大值 = 100,显示进度条显示为半填充。
- 将断点添加到这些属性的获取器中,它们没有被触发(这让我很困惑!
任何提示可能导致这种情况的原因是什么?
根据您的
问题回答
在这种情况下应使用的绑定方法是 Value="{Binding CurrentProgress, RelativeSource={RelativeSource AncestorType={x:Type GameFlowControl}}}"
。 这将向上遍历可视化树,找到第一个GameFlowControl
控件,然后从此相对位置绑定到路径。
另一种选择
作为替代方法,如果您不将UserControl
中的DataContext
用于任何其他目的,则可以使用较短的绑定方法。
首先,您需要使用如下所示将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 和 seters 触发任何断点的原因是 WPF 框架不使用它们。 它在内部直接调用GetValue(CurrentProgressProperty);
和SetValue(CurrentProgressProperty, value);
。它们只是为了方便您包含在代码中,并具有类型转换的便利性,从而在编译时进行类型检查。
如果你的代码不使用它们,那么它们将永远不会被调用。