簡體   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