繁体   English   中英

C#WPF自定义控件在设计时不响应XAML属性?

[英]C# WPF custom control not responding to XAML properties at design-time?

我创建了一个UserControl,它实际上是一个按钮。 它上面有一个图像和一个标签,我创建了两个属性来设置图像的源和标签的文本,如下所示:

        public ImageSource Icon
    {
        get { return (ImageSource)this.GetValue(IconProperty); }
        set { this.SetValue(IconProperty, value); icon.Source = value; }
    }
    public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NavigationButton));

    public string Text
    {
        get { return (string)this.GetValue(TextProperty); }
        set { this.SetValue(TextProperty, value); label.Content = value; }
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(NavigationButton));

但是,当我将控件添加到Page中时,控件将不会响应我在XAML中设置的任何属性,例如<controls:MusicButton Icon="/SuCo;component/Resources/settings.png/>不会执行任何操作。

我究竟做错了什么?

CLR性能那套依赖属性应该比调用其他任何逻辑GetValueSetValue 那是因为它们甚至可能不会被调用。 例如,XAML编译器将通过直接调用GetValue / SetValue而不是使用CLR属性来进行优化。

如果在更改依赖项属性时需要执行一些逻辑,请使用元数据:

public ImageSource Icon
{
    get { return (ImageSource)this.GetValue(IconProperty); }
    set { this.SetValue(IconProperty, value); }
}

public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NavigationButton), new FrameworkPropertyMetadata(OnIconChanged));

private static void OnIconChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
    //do whatever you want here - the first parameter is your DependencyObject
}

编辑

在我的第一个答案中,我假设您控件的XAML(无论是来自模板还是直接位于UserControl中)已正确连接到属性。 您尚未向我们展示XAML,因此这可能是一个错误的假设。 我希望看到类似的东西:

<StackPanel>
    <Image Source="{Binding Icon}"/>
    <TextBlock Text="{Binding Text}"/>
</StackPanel>

而且-重要的是-您的DataContext必须设置为控件本身。 您可以通过各种不同的方式来执行此操作,但是这里有一个非常简单的示例,可以通过后面的代码进行设置:

public YourControl()
{
    InitializeComponent();
    //bindings without an explicit source will look at their DataContext, which is this control
    DataContext = this;
}

您是否也尝试过设置text属性? 图像来源可能只是错误的。 文字更直接。

另外,在您的示例中,您错过了引号。 因此,如果它是从您的真实代码中复制的,则可能需要检查一下。

除了那些不太可能引起您的问题的小原因,我建议在代码中设置属性以检查是否有任何作用。 如果有,那么您应该真正检查XAML。

由于您尚未发布其余代码,因此我无法真正判断您是否在其他地方可能会影响控件。

是的,我知道我不是很有帮助,但是我与WPF的合作只有一段时间了。 希望它能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM