在WPF UserControl上,依赖属性对我不起作用

时间:2012-02-02 02:36:48

标签: c# wpf xaml user-controls dependency-properties

我使用依赖项属性创建了自己的用户控件,并将其添加到我的主窗口,我现在希望能够设置依赖项属性。属性没有采用我在主窗口的XAML中设置的值,我不确定我缺少什么。在代码中,我将FillBrush属性的默认值设置为Yellow。在XAML中,我将其设置为红色。单击“测试”按钮时,它会将属性显示为“黄色”。这是代码:

Window XAML

<Window x:Class="Test.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:test="clr-namespace:Test"
    Title="Window2" Height="200" Width="600">

    <StackPanel>
        <test:TestUserControl x:Name="myControl"
            FillBrush="Red" VerticalAlignment="Center" Margin="20"/>
        <Button Height="24" Width="300" Content="Test" Click="Button_Click" />
        <TextBox x:Name="debugTextBox" Margin="20"/>
    </StackPanel>
</Window>

幕后代码

public partial class Window2 : Window
{
    public static readonly DependencyProperty FillBrushProperty =
        DependencyProperty.Register("FillBrush", typeof(Brush), typeof(Window2),
        new UIPropertyMetadata(Brushes.Yellow));

    public Brush FillBrush
    {
        get { return (Brush)GetValue(FillBrushProperty); }
        set { SetValue(FillBrushProperty, value); }
    }

    public Window2() { InitializeComponent(); }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.debugTextBox.Text = 
            "Red: " + Brushes.Red +
            "  Yellow: " + Brushes.Yellow +
            "  Actual: " + this.FillBrush;
    }
}

用户控制XAML

<UserControl x:Class="Test.TestUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <TextBlock Text="User Control"/>
</UserControl>

用户控制代码

public partial class TestUserControl : UserControl
{
    public static readonly DependencyProperty FillBrushProperty =
        DependencyProperty.Register("FillBrush", typeof(Brush), typeof(TestUserControl),
        new UIPropertyMetadata(Brushes.Cyan));

    public Brush FillBrush
    {
        get { return (Brush)GetValue(FillBrushProperty); }
        set { SetValue(FillBrushProperty, value); }
    }

    public TestUserControl()
    {
        InitializeComponent();
    }
}

我错过了什么?

1 个答案:

答案 0 :(得分:1)

在XAML中,您将Fillbrush上的TestUserControl值设置为红色,但是当点击该按钮时,它会显示Fillbrush的{​​{1}}值,而不是{{ 1}}。由于Window2的{​​{1}}值未在XAML中设置,因此其默认值仍为黄色。

相关问题