1

我有各种各样的用户控件,我正在尝试查看是否可以为它们创建一个具有一些依赖属性的基类。

具体来说,我的大多数用户控件都遵循这种格式......

<UserControl DataContext="{Binding MyDataContext}" >
    <Expander IsExpanded="{Binding MyExpandedByDefault}">
        <TextBlock>Some text</TextBlock>
    </Expander>
</UserControl>

当然,通常如果这只是一次性的,我会在后面的代码中为上述用户控件编写依赖属性。但是,由于我有多个遵循相同格式的用户控件,所以我想在基类中放置类似以下内容...

public bool ExpandedByDefault
{
    get { return (bool)GetValue(ExpandedByDefaultProperty); }
    set { SetValue(ExpandedByDefaultProperty, value); }
}

public static readonly DependencyProperty ExpandedByDefaultProperty =
    DependencyProperty.Register("ExpandedByDefault", typeof(bool), typeof(MyBaseView), new UIPropertyMetadata());

我希望它在某个地方被继承,所以在我的主窗口中我可以做类似的事情......

<Window>
    <StackPanel>
        <my:Alpha ExpandedByDefault="True" />
        <my:Bravo ExpandedByDefault="False" />
    </StackPanel>
</Window>

谢谢

编辑:

我做了一个这样的基类......

public class ViewBase : UserControl
{
    public static readonly DependencyProperty ExpandedByDefaultProperty =
                 DependencyProperty.Register("ExpandedByDefault",
                                             typeof(bool),
                                             typeof(FiapaDbViewerBase),
                                             new FrameworkPropertyMetadata());

    public bool ExpandedByDefault
    {
        get
        {
            return (bool)this.GetValue(ExpandedByDefaultProperty);
        }
        set
        {
            this.SetValue(ExpandedByDefaultProperty, value);
        }
    }
}

但是当我尝试在我的用户控件背后的代码中继承它时......

public partial class MyUserControl : ViewBase
{
    public MyUserControl()
    {
        InitializeComponent();
    }
}

我收到一条错误消息

Partial declarations of 'MyUserControl' must not specify different base classes

而且我在我的解决方案中找不到部分类的另一部分???我已经尝试在整个解决方案中搜索它......

4

1 回答 1

2

你可以继承。像这样:

  1. 定义一个基类:

    public class BaseExpanderUC : UserControl
    {
        public bool ExpandedByDefault
        {
            get { return (bool)GetValue(ExpandedByDefaultProperty); }
            set { SetValue(ExpandedByDefaultProperty, value); }
        }
    
        public static readonly DependencyProperty ExpandedByDefaultProperty =
            DependencyProperty.Register("ExpandedByDefault", typeof(bool), typeof(MyBaseView), new UIPropertyMetadata(false));
    }
    
  2. 定义一个继承的类:

    public class Alpha : BaseExpanderUC{}
    public class Bravo : BaseExpanderUC{}
    
  3. 在每个继承类(上面的 Alpha 和 Bravo)的每个 XAML 中,使用这个 makup:

    <BaseExpanderUC>
        <Expander IsExpanded="{Binding MyExpandedByDefault,
                                       RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:BaseExpanderUC}}}">
            <TextBlock>Some text</TextBlock>
        </Expander>
    </BaseExpanderUC>
    

    其中“local”是 BaseExpanderUC 命名空间的 xmlns。

这将要求您为每个 UC 定义 UI。如果您可以为所有控件提供通用 UI,我强烈建议您使用自定义控件(可能继承 Expander)。然后,您只需定义一次 UI,在ControlTemplate.

于 2013-04-09T15:16:05.990 回答