【问题标题】:Dependency property is not working for me on a WPF UserControl依赖属性在 WPF UserControl 上对我不起作用
【发布时间】:2012-02-02 02:36:47
【问题描述】:

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

窗口 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();
    }
}

我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    在 XAML 中,您将 TestUserControl 上的 Fillbrush 值设置为红色,但是当单击该按钮时,它会显示 Window2Fillbrush 值,而不是 TestUserControl。由于 Window2Fillbrush 值未在 XAML 中设置,因此它仍然具有默认值 Yellow。

    【讨论】:

    • 哦,天哪!那真是一团糟,我的错!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    相关资源
    最近更新 更多