【发布时间】:2017-07-04 20:14:26
【问题描述】:
在我的用户控件下面:
<UserControl x:Class="WpfApplication1.Controls.CircularProgressBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Transparent"
Height="{Binding ControlHeightProperty}"
Width="{Binding ControlWidthProperty}">
<UserControl.Resources>
<SolidColorBrush x:Key="progressCirclesColor" Color="#FF2E6187" />
</UserControl.Resources>
<Viewbox Width="{Binding ControlWidthProperty}" Height="{Binding ControlHeightProperty}" HorizontalAlignment="Center" VerticalAlignment="Center">
<!-- other objects -->
</Viewbox>
</UserControl>
及其与我的依赖属性的代码隐藏:
public partial class CircularProgressBar
{
public static readonly DependencyProperty ControlHeightProperty =
DependencyProperty.Register("ControlHeight", typeof(int), typeof(CircularProgressBar), new UIPropertyMetadata(45));
public static readonly DependencyProperty ControlWidthProperty =
DependencyProperty.Register("ControlWidth", typeof(int), typeof(CircularProgressBar), new UIPropertyMetadata(45));
public int ControlHeight
{
get { return (int)GetValue(ControlHeightProperty); }
set { SetValue(ControlHeightProperty, value); }
}
public int ControlWidth
{
get { return (int)GetValue(ControlWidthProperty); }
set { SetValue(ControlWidthProperty, value); }
}
}
然后从我的 wpf 主窗口:
<ctr:CircularProgressBar x:Name="progressBar" Grid.ZIndex="3"
HorizontalAlignment="Center"
VerticalAlignment="Center"
ControlHeight="100"
ControlWidth="100"/>
我要做的是从我的主窗口为我的用户控件设置宽度和高度。在上面的示例中,我试图通过依赖属性 ControlHeight 和 ControlWidth 分别将用户控件的高度和宽度设置为 100。
如果在我的主窗口中没有指定 ControlHeight 和 ControlWidth,我希望用户控件的高度和宽度设为默认值 45。
但上面的例子对我不起作用。我做错了什么?
更新工作: 正如 Clemens 所建议的,我已将代码更改为以下内容:
<UserControl x:Class="WpfApplication1.Controls.CircularProgressBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Transparent">
<UserControl.Resources>
<SolidColorBrush x:Key="progressCirclesColor" Color="#FF2E6187" />
</UserControl.Resources>
<Viewbox HorizontalAlignment="Center" VerticalAlignment="Center">
<!-- other objects -->
</Viewbox>
</UserControl>
在代码隐藏依赖属性中,不需要 ControlHeightProperty 和 ControlWidthProperty。
最后在我的 wpf 窗口中,设置典型的高度和宽度属性就足够了:
<ctr:CircularProgressBar x:Name="progressBar" Grid.ZIndex="3"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Height="100"
Width="100"/>
【问题讨论】:
-
您是否遇到绑定错误?
-
除了问题中的实际问题,你知道这些属性没有意义,因为已经有了Width和Height?
-
@Clemens 我想他只想在用户控件中定义控件的大小。用户控件的大小可以是其他任何值。
-
@NtFreX 你看到 UserControl 本身的 Width 和 Height 绑定了吗?然后 Viewbox 将填充 UserControl 的整个区域,因此那里的绑定毫无意义。
-
@Clemens 不,我没有,它可能会被添加。但你是对的。如果他想设置用户控件的大小,这不是这样做的。
标签: c# wpf xaml dependency-properties