【问题标题】:UserControl with Dependency property具有 Dependency 属性的 UserControl
【发布时间】:2014-10-16 09:44:23
【问题描述】:

我创建了一个名为 TagItem 的 UserControl 类,它目前只包含一个名为 mainButton 的 Button。

它有一个名为 DisplayedTag 的依赖属性,它是 Tag 的类型(一个包含我的标签数据的简单类)。我的目标是当用户从 XAML 中设置 DisplayedTag 时 mainButton 的文本应该更新为 Tag 的 TagName。

TagItem 中的代码:

    public Tag DisplayedTag
    {
        get { return (Tag)GetValue(DisplayedTagProperty); }
        set
        {
            SetValue(DisplayedTagProperty, value);   
        }
    }

    // Using a DependencyProperty as the backing store for MyProperty. 
    // This enables animation, styling, binding, etc...
    public static DependencyProperty DisplayedTagProperty =
        DependencyProperty.Register("DisplayedTag", 
            typeof(Tag), 
            typeof(TagItem), 
            new PropertyMetadata(new Tag(), 
                OnDisplayedTagPropertyChanged));


    private static void OnDisplayedTagPropertyChanged(DependencyObject source, 
        DependencyPropertyChangedEventArgs e)
    {
        // Put some update logic here...

        Tag tag = (Tag)e.NewValue;
        mainButton.Content = tag.TagName;

    }

在 XAML 中:

<local:TagItem DisplayedTag="{Binding}"/>

这不起作用,因为 OnDisplayedTagPropertyChanged 是静态的,而 mainButton 不是。我可能在这里完全错误的轨道,并且非常感谢一些解决简单问题的指导。

【问题讨论】:

    标签: c# xaml user-controls windows-store-apps dependency-properties


    【解决方案1】:

    OnDisplayedTagPropertyChanged 回调的source 参数中,您将获得您的UserControl 派生控件。你只需要投射它,你就可以访问它的成员mainButton

    我为你的班级取了任何名字(不知道是否一切正确):

    private static void OnDisplayedTagPropertyChanged(DependencyObject source, 
        DependencyPropertyChangedEventArgs e)
    {
        MyUserControl ctrl = source as MyUserControl;
        if(ctrl == null) // should not happen
          return;
    
        Button b = ctrl.mainButton;
    
        Tag tag = (Tag)e.NewValue;
        mainButton.Content = tag.TagName;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      相关资源
      最近更新 更多