下面是我的用户控件代码片段:
然后从我的WPF主窗口开始:
我想做的是从我的主窗口中设置我的用户控件的宽度和高度。在上面的示例中,我尝试通过依赖属性 ControlHeight 和 ControlWidth 分别将用户控件的高度和宽度设置为 100。
如果从我的主窗口未指定 ControlHeight 和 ControlWidth,则希望用户控件的高度和宽度采用默认值 45。
但是上述示例对我不起作用。我做错了什么?
更新:已经工作: 正如 Clemens 建议的那样,我已将代码更改为以下内容:
在后台代码中,不需要使用ControlHeightProperty 和 ControlWidthProperty 依赖属性。最终在我的WPF窗口中,设置典型的高度和宽度属性就足够了:
<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"/>